Files
Flexera-Launcher/WEBSITE/script.js
T
TMCandClaude Opus 5.5 ea4e823df7 Website: about what Flexera adds, in a hand-made look
The owner asked for two things: stop selling what every launcher has
(Lawnchair's home screen, dock, folders, icon packs, gestures) and sell
what Flexera adds, the wave alphabet app list and swiping past the last
page for an app; and make the page look made by a person rather than by
an AI.

The page is now written in the maker's voice as field notes: a serif on
light paper, the app's own colours, the phones drawn to the app's
measurements with notes in the margin on why things are the way they
are. "The wave alphabet" tells the list and its alphabet chapter by
chapter; "Past the last page" is the one black section, because quick
launch is a black page, and says it needs Android 12 and is off until an
app is chosen. "Smaller things I added" lists full-screen folders
(marked "Coming in 0.16.0", which turns into "New in 0.16.0" once
VERSION reaches it), the left-handed mode and the two widgets. The
playground and a shorter timed test stay; "What goes online" is a table
that says exactly what each request sends, including the clock weather's
user agent before and after 0.16.0; installing and the FAQ close the
page.

Gone: the gradient headlines, bracketed section numbers, marquees, the
rotating badge, stickers, the stats row, the card grid, ghost words, the
neon palette, the tilted phone, magnetic buttons, the custom cursor,
reveal-on-scroll and the Unbounded, Space Grotesk and JetBrains Mono
fonts (their files are deleted; the serif is a system font stack, and
Outfit stays for the phones). The phone model's alphabet is a keyboard
and screen-reader slider. Still no build step and nothing loaded from
any other server; the version shown is 0.15.0.

Made by a workflow of three proposals, two judges, a spec, a builder,
two critics (AI tells; QA and truth against the app's code) and a fix
pass, then checked in headless Chrome at phone and desktop sizes: no
horizontal scroll, no console errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:58:36 +01:00

1904 lines
80 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Flexera Launcher website. Plain JavaScript, no libraries, nothing loaded from elsewhere.
*
* The phone is drawn here at the launcher's own measurements, five times over: two stills in the
* top figure, one the scroll position drives through the story's six chapters, one people can
* use, and the list phone of the timed test. All of them draw the same state object (see blank()),
* so a picture of the phone is a pure function of that state: the story computes it from the
* scroll position, the playground animates it from gestures. */
(() => {
'use strict';
/** The version shown on the page. Change it here after a release. */
const VERSION = '0.15.0';
/* The phone is drawn at 390 x 844, one pixel per dp; the numbers below are the app's own. */
const W = 390, H = 844;
const STATUS_H = 40, NAV_H = 24;
const LIST_TOP = STATUS_H; // FlexeraDrawer: rows are cut at the status bar's lower edge
const SEARCH_BLOCK = 68; // the search field over the list's top padding: 8 + 48 + 12
const LIST_END = NAV_H + 16;
const SIDE = 14, CW = (W - 2 * SIDE) / 4, RH = 104, GRID_TOP = 56, MENU_X = 120, CLOCK_W = 4 * CW - 36, DEFAULT_WEIGHT = 300;
// ClockWidgetView: small and large figures against medium ones (0.5, 0.8 and 1.25 icon heights)
const CLOCK_PX = 88, CLOCK_SMALL = 0.625, CLOCK_LARGE = 1.25;
// flexera/res/values/flexera_dimens.xml
const EDGE_INSET = 30, LETTER_GAP = 20, STRIP_MARGIN = 16, STRIP_BOTTOM_OFFSET = 40;
const TOUCH_W = 60, HOME_TOUCH_W = 40, FINGER_GAP = 104, MIN_REACH = 96, WAVE_W = 104, FAR_MARGIN = 66;
const BUBBLE_R = 20, BUBBLE_GAP = 38, BUBBLE_EDGE = 6, HOLD_MIN_SWIPE = 32;
// WaveAlphabetView.kt
const FULL_ALPHABET = 26, WAVE_SHARE = 0.36, SELECTED_GROWTH = 0.25, SCRUB_DIM = 0.55, SCRUB_DIM_AT_EDGE = 0.35;
const GROUP_MIDDLE = 0.5, GROUP_HIGHEST_TOP = 0.22, REST_BEFORE_SCRUB_MS = 130, PRESS_IN_MS = 110, PRESS_OUT_MS = 220;
const BACK_ZONE = 24; // Android's Back swipe strip (systemGestureInsets), about 24 dp
// FlexeraDrawer.kt, FlexeraEdgeScrubController.kt, NoButtonNavbarToOverviewTouchController.java
const BACKDROP = 0.78, FADE_COMPLETE_AT = 0.6, MIN_SCRUB_MS = 200, OPEN_FROM_SCRUB_MS = 120, HOLD_STILL_MS = 150;
// QuickLaunchPage.kt, QuickLaunch.kt
const OPEN_DISTANCE = 0.4, HOME_DIM = 0.35, FLICK_DISTANCE = 0.02, FLICK_SPEED = 600, MIN_SETTLE_SPEED = 1500, MIN_SETTLE_MS = 150, MAX_SETTLE_MS = 300;
// FullScreenFolders.kt, PictureWidgetView.kt
const FOLDER_BOTTOM = 16, FOLDER_NAME_H = 24, PICTURE_MS = 10000;
const STORY_END = 6;
const REST = [0.95, 0.4, 0.7, 0.5, 0.6, 0.4]; // each chapter's still frame, for reduced motion
const look = { lefty: false, comfy: false };
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
let reduced = motion.matches;
/* ------------------------------------------------------------------ math */
const clamp = (v, a = 0, b = 1) => (v < a ? a : v > b ? b : v);
const lerp = (a, b, t) => a + (b - a) * t;
const seg = (t, a, b) => clamp((t - a) / (b - a));
const inOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const outCubic = (t) => 1 - Math.pow(1 - t, 3);
const linear = (t) => t;
const smooth = (t) => t * t * (3 - 2 * t);
const E = (t, a, b) => inOut(seg(t, a, b));
/** Eased value along key points [[t, value], ...]. */
function keys(t, pts) {
if (t <= pts[0][0]) return pts[0][1];
for (let i = 1; i < pts.length; i++) {
if (t <= pts[i][0]) return lerp(pts[i - 1][1], pts[i][1], inOut(seg(t, pts[i - 1][0], pts[i][0])));
}
return pts[pts.length - 1][1];
}
/** A pull against a wall: follows the finger at first, then gives less and less. */
const rubber = (x) => Math.sign(x) * 96 * (1 - Math.exp(-Math.abs(x) / 140));
/* ------------------------------------------------------------------ data */
/** Themed icons, tinted from the wallpaper, as Android 13 and Lawnchair draw them... */
const THEMED = { bg: '#d5e7dc', fg: '#1e4a3b' };
/** ...and the apps that don't support it, which keep colours of their own. */
const ODD = {
Banking: { bg: '#1f5fbf', fg: '#fff' },
Shop: { bg: '#ee8a2c', fg: '#fff' },
Stocks: { bg: '#1c1d1f', fg: '#3ddc84' },
Authenticator: { bg: '#fff', fg: '#3c4043' },
Games: { bg: 'radial-gradient(circle at 32% 30%, #ffd166 0 16%, transparent 17%), linear-gradient(155deg, #34295f, #b8437a)', fg: '#fff' },
};
const APPS = [
['Authenticator', 'shield'],
['Banking', 'bank'],
['Books', 'book'],
['Browser', 'globe'],
['Calculator', 'calc'],
['Calendar', 'cal'],
['Camera', 'camera'],
['Clock', 'clock'],
['Contacts', 'person'],
['Files', 'files'],
['Fitness', 'pulse'],
['Gallery', 'image'],
['Mail', 'mail'],
['Maps', 'map'],
['Messages', 'msg', 'Bike shop: Your repair is ready to collect'],
['Music', 'music'],
['News', 'news'],
['Notes', 'notes'],
['Phone', 'phone'],
['Podcasts', 'mic'],
['Recorder', 'wave'],
['Settings', 'sliders'],
['Shop', 'bag'],
['Translate', 'translate'],
['Travel', 'plane'],
['Video', 'play'],
['Wallet', 'wallet'],
['Weather', 'sun'],
['Zen', 'moon'],
['Alarm', 'alarm'],
['Compass', 'compass'],
['Docs', 'notes'],
['Games', 'game'],
['Health', 'heart'],
['Lens', 'search'],
['Measure', 'ruler'],
['Radio', 'radio'],
['Stocks', 'chart'],
['Tasks', 'check'],
['Vault', 'lock'],
].map(([n, g, note]) => ({ n, g, note, look: ODD[n] || THEMED })).sort((a, b) => a.n.localeCompare(b.n));
const APP = Object.fromEntries(APPS.map((a) => [a.n, a]));
const LETTERS = [...new Set(APPS.map((a) => a.n[0]))];
const L = (letter) => LETTERS.indexOf(letter);
const FOLDERS = {
media: { title: 'Media', apps: ['Video', 'Podcasts', 'Gallery', 'Books', 'News'] },
tools: { title: 'Tools', apps: ['Calculator', 'Files', 'Recorder', 'Translate', 'Notes', 'Authenticator'] },
};
const HOME = [
[
{ k: 'clock', c: 0, r: 0, w: 4, h: 2 },
{ k: 'pics', c: 2, r: 2, w: 2, h: 2 },
{ app: 'Maps', c: 0, r: 2 }, { app: 'Music', c: 1, r: 2 },
{ app: 'Mail', c: 0, r: 3 }, { app: 'Calendar', c: 1, r: 3 },
{ folder: 'media', c: 0, r: 4 }, { app: 'Weather', c: 1, r: 4 }, { app: 'Wallet', c: 2, r: 4 }, { folder: 'tools', c: 3, r: 4 },
{ app: 'Phone', c: 0, r: 5 }, { app: 'Messages', c: 1, r: 5, dot: true }, { app: 'Browser', c: 2, r: 5 }, { app: 'Camera', c: 3, r: 5 },
],
[
{ app: 'Fitness', c: 0, r: 0 }, { app: 'Zen', c: 1, r: 0 }, { app: 'Travel', c: 2, r: 0 }, { app: 'Shop', c: 3, r: 0 },
{ app: 'Banking', c: 0, r: 1 }, { app: 'Contacts', c: 1, r: 1 }, { app: 'Clock', c: 2, r: 1 }, { app: 'Settings', c: 3, r: 1 },
{ app: 'Translate', c: 0, r: 2 }, { app: 'Recorder', c: 1, r: 2 },
],
];
/* ------------------------------------------------------------------ the phone */
/** A short vibration on phones that have one, like the launcher's tick per letter. */
function buzz(ms = 7) {
if (reduced || !navigator.vibrate) return;
if (navigator.userActivation && !navigator.userActivation.hasBeenActive) return; // Chrome refuses it before a tap, and says so
try {
navigator.vibrate(ms);
} catch (_) { /* some browsers refuse without a user gesture */ }
}
const gl = (id, cls = 'gl') => `<svg class="${cls}" aria-hidden="true"><use href="#g-${id}"/></svg>`;
function icon(app, cls = '') {
return `<span class="ic${cls}" style="--bg:${app.look.bg};--fg:${app.look.fg}">${gl(app.g, '')}</span>`;
}
function cellMarkup(it) {
const box = `left:${SIDE + it.c * CW}px;top:${GRID_TOP + it.r * RH}px;width:${(it.w || 1) * CW}px;height:${(it.h || 1) * RH}px`;
if (it.k === 'clock') {
return `<div class="w-clock" data-key="clock" style="${box}">
<div class="clk__line clk__time"><span data-time>9:41</span></div>
<div class="clk__line clk__date"><span data-date>Thursday, November 12</span></div>
<div class="clk__line clk__wx"><span>18&deg; &middot; Clear</span></div></div>`;
}
if (it.k === 'pics') {
return `<div class="w-pics" data-key="pics" style="${box}"><div class="pics">
<i class="pic pic--a on"></i><i class="pic pic--b"></i><i class="pic pic--c"></i></div></div>`;
}
if (it.folder) {
const f = FOLDERS[it.folder];
return `<div class="cell" data-key="${it.folder}" data-folder="${it.folder}" style="${box}">
<span class="fic">${f.apps.slice(0, 4).map((n) => icon(APP[n], ' ic--mini')).join('')}</span>
<span class="lbl">${f.title}</span></div>`;
}
const app = APP[it.app];
return `<div class="cell" data-key="${app.n}" data-app="${app.n}" style="${box}">${icon(app)}${it.dot ? '<i class="ndot"></i>' : ''}<span class="lbl">${app.n}</span></div>`;
}
function listMarkup() {
let html = `<div class="search">${gl('search')}<span>Search apps and more</span></div>`;
for (const letter of LETTERS) {
html += `<div class="grp" data-letter="${letter}"><div class="hdr">${letter}</div>`;
for (const a of APPS.filter((x) => x.n[0] === letter)) {
html += `<div class="row" data-row="${a.n}">${icon(a)}
<span class="row__t"><span class="row__n">${a.n}</span>${a.note ? `<span class="row__p">${a.note}</span>` : ''}</span></div>`;
}
html += '</div>';
}
return html;
}
function phoneMarkup() {
const pages = HOME.map((items, pi) => `<div class="page" style="left:${pi * W}px">${items.map(cellMarkup).join('')}</div>`).join('');
const dots = HOME.map((_, i) => `<i${i ? '' : ' class="on"'}></i>`).join('');
return `<div class="phone" aria-hidden="true"><div class="screen">
<div class="world"><div class="wall"></div><div class="wall wall--blur"></div>
<div class="home"><div class="pages">${pages}</div><div class="pagedots">${dots}</div></div>
<div class="home home--blur"><div class="home__blurred"><div class="pages">${pages}</div></div></div>
</div>
<div class="qdim"></div><div class="qpage"></div><div class="scrim"></div>
<div class="ffolder"><div class="ffolder__grid"></div><div class="ffolder__name"></div></div>
<div class="drawer"><div class="drawer__in">
<div class="list">${listMarkup()}</div>
<div class="sdim"></div>
<div class="alpha"><span class="alpha__s">${gl('search', 'gl')}</span>${LETTERS.map((l) => `<span class="alpha__l">${l}</span>`).join('')}</div>
<div class="bubble"></div>
</div></div>
<div class="menu">
<div class="mi">${gl('info')}App info</div>
<div class="mi">${gl('widgets')}Widgets</div>
<div class="mi">${gl('edit')}Customize</div>
<div class="mi mi--hide">${gl('eyeoff')}Hide app</div>
</div>
<div class="snack"><span class="snack__t">Podcasts is hidden</span><button type="button" class="snack__undo" tabindex="-1">Undo</button></div>
<div class="sheet"><i class="sheet__grab"></i><h4>Clock</h4>
<p class="sheet__h">Alignment</p>
<div class="seg" data-seg="align"><span data-v="0" data-k="align-0">Left</span><span data-v="0.5" data-k="align-0.5">Center</span><span data-v="1" data-k="align-1">Right</span></div>
<p class="sheet__h">Size</p>
<div class="seg" data-seg="size"><span data-v="${CLOCK_SMALL}" data-k="size-s">Small</span><span data-v="1" data-k="size-m">Medium</span><span data-v="${CLOCK_LARGE}" data-k="size-l">Large</span></div>
<p class="sheet__h">Weight</p>
<div class="seg" data-seg="weight"><span data-v="100" data-k="weight-100">Thin</span><span data-v="300" data-k="weight-300">Light</span><span data-v="400" data-k="weight-400">Regular</span><span data-v="700" data-k="weight-700">Bold</span></div>
</div>
<div class="app">
<div class="cam__view"><i class="cam__book"></i><i class="cam__mug"></i><i class="cam__grid"></i><i class="cam__focus"></i></div>
<div class="cam__modes"><span>Video</span><span class="on">Photo</span><span>Portrait</span></div>
<div class="cam__bar"><i class="cam__thumb"></i><i class="cam__shutter"></i><i class="cam__flip">${gl('flip')}</i></div>
</div>
<div class="sbar"><span class="sbar__time">9:41</span><span class="sbar__icons"><span class="sbar__sig"><i></i><i></i><i></i><i></i></span><span class="sbar__bat"></span></span></div>
<i class="notch"></i>
<i class="gbar"></i>
<div class="finger"><i class="finger__ring"></i></div>
<svg class="marks" viewBox="0 0 390 844" aria-hidden="true"></svg>
</div></div>`;
}
/** Everything the phone can show. Numbers are 0..1 unless noted. */
function blank() {
return {
drawer: 0,
list: 0, // px the app list is scrolled
scrub: 0, // where the finger is on the alphabet: -1 the magnifier, 0 to 16 the letters, fractional
press: 0, // how far the wave is out
scrubX: null, // the finger's x while it scrubs; null: on the letters
folder: 0,
folderId: 'media',
pull: 0, // px the pages are dragged sideways
page: 0,
quick: 0, // how far quick launch's black page is in
quickSide: 'right',
app: 0, // the app quick launch opened, on screen
shutter: 0,
sheet: 0,
align: 0, // 0 left, .5 centre, 1 right
weight: DEFAULT_WEIGHT,
size: 1, // the clock's figures against medium ones
menu: 0,
menuY: 420,
menuPick: 0,
held: null,
hidden: {},
snack: 0,
snackText: 'Podcasts is hidden',
finger: { x: 195, y: 600, o: 0, press: 0, ring: 0 },
marks: { spacing: 0, inset: 0, middle: 0, thumb: 0, band: 0, threshold: 0 },
};
}
/** Offset of el inside ancestor, summed along the offsetParent chain (ignores transforms). */
function offsetIn(el, ancestor) {
let x = 0;
let y = 0;
while (el && el !== ancestor) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
return { x, y };
}
/** Where the letters go (WaveAlphabetView.computeLayout): a zone as tall as 26 letters, low on the edge. */
function computeStrip(stops) {
const top = LIST_TOP + SEARCH_BLOCK + STRIP_MARGIN, bottom = H - NAV_H - STRIP_MARGIN, avail = bottom - top;
const spacing = Math.min(LETTER_GAP, avail / stops), block = spacing * stops;
const zone = Math.max(block, Math.min(avail, spacing * (FULL_ALPHABET + 1)));
const zoneBottom = bottom - Math.min(STRIP_BOTTOM_OFFSET, avail - zone);
const t = zoneBottom - zone + (zone - block) / 2;
return { top: t, bottom: t + block, spacing, y: Array.from({ length: stops }, (_, i) => t + spacing * (i + 0.5)) };
}
const SVG_NS = 'http://www.w3.org/2000/svg';
function svgEl(parent, tag, attrs = {}) {
const el = document.createElementNS(SVG_NS, tag);
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
parent.appendChild(el);
return el;
}
function setAttrs(el, attrs) {
for (const k in attrs) {
const v = attrs[k];
el.setAttribute(k, typeof v === 'number' ? String(Math.round(v * 10) / 10) : v);
}
}
/** A dimension line from (x, y1) to (x, y2), with an 8 px tick across each end. */
function vdim(d, x, y1, y2) {
setAttrs(d.line, { x1: x, y1, x2: x, y2 });
setAttrs(d.a, { x1: x - 4, y1, x2: x + 4, y2: y1 });
setAttrs(d.b, { x1: x - 4, y1: y2, x2: x + 4, y2 });
}
/** The same across: from (x1, y) to (x2, y). */
function hdim(d, x1, x2, y) {
setAttrs(d.line, { x1, y1: y, x2, y2: y });
setAttrs(d.a, { x1, y1: y - 4, x2: x1, y2: y + 4 });
setAttrs(d.b, { x1: x2, y1: y - 4, x2, y2: y + 4 });
}
class Phone {
constructor(host) {
this.host = host;
host.innerHTML = phoneMarkup();
const q = (sel) => host.querySelector(sel);
const qa = (sel) => [...host.querySelectorAll(sel)];
this.el = q('.phone');
this.screen = q('.screen');
this.r = {
world: q('.world'), home: q('.home:not(.home--blur)'), pages: q('.home:not(.home--blur) > .pages'), dots: qa('.pagedots i'),
homeBlur: q('.home--blur'), wallBlur: q('.wall--blur'), qdim: q('.qdim'), qpage: q('.qpage'), scrim: q('.scrim'),
ffolder: q('.ffolder'), ffgrid: q('.ffolder__grid'), ffname: q('.ffolder__name'),
drawer: q('.drawer'), drawerIn: q('.drawer__in'), list: q('.list'), sdim: q('.sdim'), alpha: q('.alpha'), stops: qa('.alpha > span'), bubble: q('.bubble'),
menu: q('.menu'), menuHide: q('.mi--hide'), snack: q('.snack'), snackT: q('.snack__t'),
sheet: q('.sheet'), segAlign: qa('[data-seg="align"] span'), segSize: qa('[data-seg="size"] span'), segWeight: qa('[data-seg="weight"] span'),
app: q('.app'), shutter: q('.cam__shutter'), finger: q('.finger'), ring: q('.finger__ring'), marks: q('.marks'),
clockLines: qa('.clk__line > span'), clockTime: qa('.clk__time'), time: qa('[data-time]'), date: qa('[data-date]'), stime: q('.sbar__time'),
pics: qa('.pic'),
rows: new Map(qa('.row').map((el) => [el.dataset.row, el])),
};
this.scale = 0.5;
this.picIndex = 0;
this.lefty = false;
this.comfy = false;
this.folderId = null;
this.labelW = {};
this.fillFolder('media');
this.initMarks();
this.fit();
if ('ResizeObserver' in window) new ResizeObserver(() => this.fit()).observe(host);
this.measure();
}
fit() {
const w = this.host.clientWidth;
if (!w) return;
this.scale = w / 414;
this.el.style.setProperty('--s', this.scale.toFixed(5));
this.host.style.setProperty('--s', this.scale.toFixed(5));
}
/** Reads the layout once, so that animating never has to. Call again when rows change height. */
measure() {
const r = this.r;
const g = { groupTop: {}, groupH: {}, rowTop: {}, rowH: {} };
for (const grp of r.list.querySelectorAll('.grp')) {
g.groupTop[grp.dataset.letter] = grp.offsetTop;
g.groupH[grp.dataset.letter] = grp.offsetHeight;
}
for (const [name, el] of r.rows) {
g.rowTop[name] = el.offsetTop;
g.rowH[name] = el.offsetHeight || 50;
}
g.listH = r.list.offsetHeight;
g.maxScroll = Math.max(0, LIST_TOP + g.listH + LIST_END - H);
g.strip = computeStrip(LETTERS.length + 1);
r.alpha.style.top = `${g.strip.top}px`;
r.alpha.style.height = `${g.strip.bottom - g.strip.top}px`;
g.alphaX = this.lefty ? EDGE_INSET : W - EDGE_INSET;
g.letterY = g.strip.y.slice(1);
g.home = {};
for (const el of this.host.querySelectorAll('.home:not(.home--blur) .page:first-child [data-key]')) {
const target = el.querySelector('.ic, .fic') || el;
const p = offsetIn(target, this.screen);
g.home[el.dataset.key] = { x: p.x + target.offsetWidth / 2, y: p.y + target.offsetHeight / 2 };
}
const sheetTop = H - r.sheet.offsetHeight;
g.seg = {};
for (const sp of this.host.querySelectorAll('.seg span')) {
const p = offsetIn(sp, r.sheet);
g.seg[sp.dataset.k] = { x: p.x + sp.offsetWidth / 2, y: sheetTop + p.y + sp.offsetHeight / 2 };
}
const m = offsetIn(r.menuHide, r.menu);
g.menuHide = { x: m.x + r.menuHide.offsetWidth / 2, y: m.y + r.menuHide.offsetHeight / 2 };
g.menuH = r.menu.offsetHeight || 212;
this.g = g;
this.labelW = {}; // the marks' labels are measured again, in case the font has come in since
}
/** The two settings from the app: the alphabet on the left edge, and comfy rows. */
setLook(look) {
this.lefty = !!look.lefty;
this.comfy = !!look.comfy;
this.screen.classList.toggle('is-lefty', this.lefty);
this.screen.classList.toggle('is-comfy', this.comfy);
this.host.classList.toggle('is-lefty', this.lefty);
for (const el of this.r.rows.values()) { // row heights changed
el._h = 0;
el._hx = -1;
}
this.measure();
}
fillFolder(id) {
this.folderId = id;
const f = FOLDERS[id];
this.r.ffgrid.innerHTML = f.apps.map((n) => `<div class="ffolder__app">${icon(APP[n])}<span>${n}</span></div>`).join('');
this.r.ffname.textContent = f.title;
this.folderTop = H - NAV_H - FOLDER_BOTTOM - FOLDER_NAME_H - Math.ceil(f.apps.length / 4) * RH; // Media: 572
}
/** Where the list lands for stop i (WaveAlphabetView.scrollListTo): the group's middle on the list's middle. */
scrollFor(i) {
const idx = Math.round(i);
if (idx < 0) return 0; // the magnifier: back to the search field
const letter = LETTERS[clamp(idx, 0, LETTERS.length - 1)];
const listH = H - LIST_TOP;
const want = Math.max(listH * GROUP_HIGHEST_TOP, listH * GROUP_MIDDLE - this.g.groupH[letter] / 2);
return clamp(this.g.groupTop[letter] - want, 0, this.g.maxScroll);
}
/** scrollFor between letters, snapping near each one, for scroll-driven scrubbing. */
scrollAt(f) {
const a = Math.floor(f);
const b = Math.ceil(f);
if (a === b) return this.scrollFor(a);
return lerp(this.scrollFor(a), this.scrollFor(b), smooth(seg(f - a, 0.3, 0.7)));
}
letterYAt(f) {
const s = this.g.strip;
return clamp(s.y[0] + (f + 1) * s.spacing, s.y[0], s.y[s.y.length - 1]);
}
letterAtY(y) {
const s = this.g.strip;
return clamp((y - s.y[0]) / s.spacing - 1, -1, LETTERS.length - 1);
}
rowY(name, scroll) {
return LIST_TOP + this.g.rowTop[name] + this.g.rowH[name] / 2 - scroll;
}
tick(now, date) {
for (const el of this.r.time) if (el.textContent !== now) el.textContent = now;
if (this.r.stime.textContent !== now) this.r.stime.textContent = now;
for (const el of this.r.date) if (el.textContent !== date) el.textContent = date;
}
nextPicture() {
this.picIndex = (this.picIndex + 1) % 3;
this.r.pics.forEach((p, i) => p.classList.toggle('on', i % 3 === this.picIndex));
}
render(s) {
const r = this.r;
const g = this.g;
const css = (el, prop, val) => {
const k = '_' + prop;
if (el[k] !== val) {
el[k] = val;
el.style[prop] = val;
}
};
const d = s.drawer;
const f = s.folder;
const q = s.quick;
// Quick launch: home and wallpaper move aside with the finger (QuickLaunchPage.apply).
const dir = s.quickSide === 'left' ? 1 : -1;
css(r.world, 'transform', q > 0.0005 ? `translateX(${(dir * q * W).toFixed(1)}px)` : '');
const qb = 1 - (1 - q) ** 2; // QuickLaunchPage.blurFor
css(r.wallBlur, 'opacity', Math.max(d, f, qb).toFixed(3));
css(r.scrim, 'opacity', (BACKDROP * Math.max(d, f)).toFixed(3));
css(r.qdim, 'opacity', (HOME_DIM * q).toFixed(3));
css(r.qpage, 'width', `${(q * W).toFixed(1)}px`);
r.qpage.classList.toggle('is-left', s.quickSide === 'left');
// Home: fades for the list; crossfades to its blurred copy behind a folder and quick launch.
const hb = Math.max(f, qb);
css(r.home, 'opacity', ((1 - d) * (1 - hb)).toFixed(3));
css(r.homeBlur, 'opacity', ((1 - d) * hb).toFixed(3));
css(r.home, 'transform', d > 0.001 ? `translateY(${(-26 * d).toFixed(1)}px) scale(${(1 - 0.05 * d).toFixed(4)})` : '');
const px = `translateX(${(-s.page * W + s.pull).toFixed(1)}px)`;
css(r.pages, 'transform', px);
css(r.homeBlur, 'transform', px);
const page = Math.round(clamp(s.page - s.pull / W, 0, HOME.length - 1));
r.dots.forEach((dot, i) => dot.classList.toggle('on', i === page));
// App list: fades in place, fully visible at 60% (FlexeraDrawer.applyOpenProgress).
css(r.drawer, 'visibility', d > 0.002 ? 'visible' : 'hidden');
css(r.drawerIn, 'opacity', Math.min(1, d / FADE_COMPLETE_AT).toFixed(3));
css(r.list, 'transform', `translateY(${(-s.list).toFixed(1)}px)`);
// The wave (WaveAlphabetView.onDraw).
const inward = this.lefty ? 1 : -1;
const baseX = g.alphaX;
const press = s.press;
const fy = this.letterYAt(s.scrub);
const fx = s.scrubX == null ? baseX : s.scrubX;
const maxReach = Math.max(MIN_REACH + 1, W - EDGE_INSET - FAR_MARGIN);
const fullReach = clamp((fx - baseX) * inward + FINGER_GAP, MIN_REACH, maxReach);
const reach = fullReach * press;
const spread = Math.max(WAVE_W, fullReach * WAVE_SHARE);
const sel = clamp(Math.round(s.scrub), -1, LETTERS.length - 1) + 1; // stop index, 0 = magnifier
r.stops.forEach((el, i) => {
const k = press > 0 ? Math.exp(-(((g.strip.y[i] - fy) / spread) ** 2)) : 0;
const on = press > 0 && i === sel;
const dx = inward * reach * k;
css(el, 'transform', Math.abs(dx) > 0.05 || on ? `translateX(${dx.toFixed(1)}px)${on ? ` scale(${(1 + SELECTED_GROWTH * press).toFixed(3)})` : ''}` : '');
css(el, 'color', on ? '#fff' : `rgba(255,255,255,${(0.7 + 0.3 * k * press).toFixed(3)})`);
el.classList.toggle('on', on);
});
const reachShare = clamp((fullReach - MIN_REACH) / (maxReach - MIN_REACH));
const overList = this.lefty ? 1 : SCRUB_DIM_AT_EDGE + (1 - SCRUB_DIM_AT_EDGE) * reachShare;
css(r.sdim, 'opacity', (SCRUB_DIM * press * overList).toFixed(3));
css(r.bubble, 'opacity', press.toFixed(3));
if (press > 0.001) {
const room = BUBBLE_R + BUBBLE_EDGE;
const cx = clamp(baseX + inward * (reach + BUBBLE_GAP * press), room, W - room);
css(r.bubble, 'transform', `translate(${(cx - BUBBLE_R).toFixed(1)}px, ${(fy - BUBBLE_R).toFixed(1)}px) scale(${press.toFixed(3)})`);
const v = sel === 0 ? '·search' : LETTERS[sel - 1];
if (r.bubble.dataset.v !== v) {
r.bubble.dataset.v = v;
r.bubble.innerHTML = sel === 0 ? gl('search', '') : v;
}
}
// Hidden apps fold away.
for (const [name, el] of r.rows) {
const x = s.hidden[name] || 0;
if (el._hx !== x) {
if (!el._h) { // the row's own height, whatever it is folded to now
const was = el.style.height;
el.style.height = '';
el._h = el.offsetHeight;
el.style.height = was;
}
el._hx = x;
el.style.height = x ? `${((1 - x) * el._h).toFixed(1)}px` : '';
el.style.opacity = x ? (1 - x).toFixed(3) : '';
}
el.classList.toggle('held', s.held === name);
}
// Long-press menu and the message after hiding.
css(r.menu, 'visibility', s.menu > 0.002 ? 'visible' : 'hidden');
css(r.menu, 'opacity', s.menu.toFixed(3));
css(r.menu, 'transform', `translate(${MENU_X}px, ${s.menuY.toFixed(1)}px) scale(${(0.9 + 0.1 * s.menu).toFixed(3)})`);
r.menuHide.classList.toggle('pick', s.menuPick > 0.5);
css(r.snack, 'visibility', s.snack > 0.002 ? 'visible' : 'hidden');
css(r.snack, 'opacity', s.snack.toFixed(3));
css(r.snack, 'transform', `translateY(${((1 - s.snack) * 26).toFixed(1)}px)`);
if (r.snackT.textContent !== s.snackText) r.snackT.textContent = s.snackText;
// Clock options sheet and the clock itself.
css(r.sheet, 'transform', `translateY(${((1 - s.sheet) * 105).toFixed(2)}%)`);
const pick = (els, v) => {
let best = null;
let bd = Infinity;
for (const e of els) {
const dd = Math.abs(+e.dataset.v - v);
if (dd < bd) {
bd = dd;
best = e;
}
}
els.forEach((e) => e.classList.toggle('on', e === best));
};
pick(r.segAlign, s.align);
pick(r.segSize, s.size);
pick(r.segWeight, s.weight);
for (const el of r.clockTime) {
css(el, 'fontWeight', String(Math.round(s.weight)));
css(el, 'fontSize', Math.abs(s.size - 1) > 0.001 ? `${(CLOCK_PX * s.size).toFixed(1)}px` : '');
}
for (const sp of r.clockLines) {
css(sp, 'transform', s.align > 0.001 ? `translateX(${(s.align * (CLOCK_W - sp.offsetWidth)).toFixed(1)}px)` : '');
}
// Full-screen folder (0.16.0).
if (s.folderId !== this.folderId) this.fillFolder(s.folderId);
css(r.ffolder, 'visibility', f > 0.002 ? 'visible' : 'hidden');
css(r.ffolder, 'opacity', Math.min(1, f * 1.4).toFixed(3));
css(r.ffolder, 'transform', f < 0.999 ? `translateY(${((1 - f) * 24).toFixed(1)}px)` : '');
// The app quick launch opened: there at once, no animation.
css(r.app, 'visibility', s.app ? 'visible' : 'hidden');
css(r.shutter, 'transform', s.shutter ? 'scale(.86)' : '');
// The finger that shows each gesture.
const fg = s.finger;
css(r.finger, 'opacity', fg.o.toFixed(3));
if (fg.o > 0.001) {
css(r.finger, 'transform', `translate(${fg.x.toFixed(1)}px, ${fg.y.toFixed(1)}px) scale(${(1 - 0.16 * fg.press).toFixed(3)})`);
}
const ring = fg.ring.toFixed(3);
if (r.ring._ring !== ring) {
r.ring._ring = ring;
r.ring.style.setProperty('--ring', ring);
}
this.drawMarks(s);
}
/** The measurement marks: one group per mark, built once, faded by its weight in s.marks. */
initMarks() {
const svg = this.r.marks;
const label = (g) => {
const lg = svgEl(g, 'g', { class: 'mk__label' });
return { rect: svgEl(lg, 'rect', { rx: '4', height: '20' }), text: svgEl(lg, 'text') };
};
const dim = (g) => ({ line: svgEl(g, 'line'), a: svgEl(g, 'line'), b: svgEl(g, 'line') });
const mark = (build) => {
const g = svgEl(svg, 'g', { class: 'mk', opacity: '0' });
return Object.assign({ g }, build(g));
};
this.mk = {
spacing: mark((g) => ({ dim: dim(g), label: label(g) })),
inset: mark((g) => ({ back: svgEl(g, 'rect', { class: 'area' }), dim: dim(g), label: label(g), backLabel: label(g) })),
middle: mark((g) => ({ bracket: svgEl(g, 'path'), tick: svgEl(g, 'path') })),
thumb: mark((g) => ({ circle: svgEl(g, 'circle', { class: 'dash', r: '70' }) })),
band: mark((g) => ({ area: svgEl(g, 'rect', { class: 'area area--dashed' }) })),
threshold: mark((g) => ({ line: svgEl(g, 'line', { class: 'dash' }), label: label(g) })),
};
}
/** A label on a dark chip: its text at x (start, middle or end) and its middle at cy. */
markLabel(lb, text, x, cy, anchor) {
if (lb.text.textContent !== text) lb.text.textContent = text;
setAttrs(lb.text, { x, y: cy + 5, 'text-anchor': anchor });
let tw = this.labelW[text];
if (!tw) {
tw = lb.text.getComputedTextLength();
if (tw > 0) this.labelW[text] = tw;
}
const bw = tw + 12;
const bx = anchor === 'start' ? x - 6 : anchor === 'end' ? x - tw - 6 : x - bw / 2;
setAttrs(lb.rect, { x: bx, y: cy - 10, width: bw });
}
drawMarks(s) {
const m = this.mk;
const g = this.g;
const w = s.marks;
const left = this.lefty;
const st = g.strip;
for (const key of Object.keys(m)) {
const v = w[key] > 0.001 ? Math.min(1, w[key]).toFixed(3) : '0';
if (m[key].g._o !== v) {
m[key].g._o = v;
m[key].g.setAttribute('opacity', v);
}
}
if (w.spacing > 0.001) { // from A to B
vdim(m.spacing.dim, g.alphaX + 20 * (left ? 1 : -1), st.y[1], st.y[2]);
this.markLabel(m.spacing.label, '20 dp', g.alphaX, st.top - 14, 'middle');
}
if (w.inset > 0.001) { // the letters' distance from the edge, and Android's Back strip
hdim(m.inset.dim, g.alphaX, left ? 0 : W, st.bottom + 14);
setAttrs(m.inset.back, { x: left ? 0 : W - BACK_ZONE, y: st.top, width: BACK_ZONE, height: st.bottom - st.top });
this.markLabel(m.inset.label, '30 dp', left ? 2 : 388, 710, left ? 'start' : 'end');
this.markLabel(m.inset.backLabel, 'Back', left ? 2 : 388, 300, left ? 'start' : 'end');
}
if (w.middle > 0.001) { // the chosen group, bracketed, and the list's middle
const letter = LETTERS[clamp(Math.round(s.scrub), 0, LETTERS.length - 1)];
const top = (LIST_TOP + g.groupTop[letter] - s.list).toFixed(1);
const bottom = (LIST_TOP + g.groupTop[letter] + g.groupH[letter] - s.list).toFixed(1);
const mid = LIST_TOP + (H - LIST_TOP) / 2;
m.middle.bracket.setAttribute('d', left ? `M374 ${top}H380V${bottom}H374` : `M16 ${top}H10V${bottom}H16`);
m.middle.tick.setAttribute('d', left ? `M380 ${mid}H372` : `M10 ${mid}H18`);
}
if (w.thumb > 0.001) setAttrs(m.thumb.circle, { cx: s.finger.x, cy: s.finger.y });
if (w.band > 0.001) { // the home screen's band, where nothing shows
setAttrs(m.band.area, { x: left ? 0 : W - HOME_TOUCH_W, y: st.top - 16, width: HOME_TOUCH_W, height: st.bottom - st.top + 32 });
}
if (w.threshold > 0.001) { // quick launch opens past this line
const x = s.quickSide === 'left' ? W * OPEN_DISTANCE : W * (1 - OPEN_DISTANCE);
setAttrs(m.threshold.line, { x1: x, y1: 64, x2: x, y2: 780 });
this.markLabel(m.threshold.label, '40%', x, 52, 'middle');
}
}
}
/* ------------------------------------------------------------------ the top figure */
/** One still frame: the list scrubbed to F, the thumb on the letters. */
function heroState(ph) {
const s = blank();
s.drawer = 1;
s.scrub = L('F');
s.press = 1;
s.list = ph.scrollFor(s.scrub);
s.finger = { x: ph.g.alphaX, y: ph.letterYAt(s.scrub), o: 1, press: 1, ring: 0 };
s.marks.thumb = 1;
return s;
}
/** The other still: past the last page, the black page just over the line where letting go opens the app. */
function quickState() {
const s = blank();
s.page = HOME.length - 1;
s.quickSide = 'right';
s.quick = 0.46;
s.finger = { x: 330 - s.quick * W, y: 430, o: 1, press: 1, ring: 0 };
s.marks.threshold = 1;
return s;
}
/** Draws the two stills and puts each margin note level with what it describes, with a leader to the phone's edge. */
function setupHero(ph, quick) {
const fig = document.querySelector('[data-fig]');
const svg = fig && fig.querySelector('[data-leaders]');
if (!fig || !svg) {
return () => {
ph.render(heroState(ph));
if (quick) quick.render(quickState());
};
}
const notes = [...fig.querySelectorAll('[data-to]')];
const wide = window.matchMedia('(min-width: 700px)');
return function draw() {
ph.fit(); // a window resize reaches here before the phone's own ResizeObserver does
if (quick) {
quick.fit();
quick.render(quickState());
}
const s = heroState(ph);
ph.render(s);
fig.classList.toggle('is-lefty', look.lefty);
svg.replaceChildren();
if (!wide.matches) {
notes.forEach((n) => { n.style.top = ''; });
return;
}
const fr = fig.getBoundingClientRect();
const sr = ph.screen.getBoundingClientRect();
const pr = ph.el.getBoundingClientRect();
const k = sr.width / W;
const target = { thumb: s.finger.y };
for (const n of notes) {
const box = n.parentElement.getBoundingClientRect();
const y = sr.top + target[n.dataset.to] * k;
n.style.top = `${(y - box.top - 11).toFixed(1)}px`; // the first line's middle on the target
const nr = n.getBoundingClientRect();
const left = box.right <= pr.left + 1;
const x1 = (left ? nr.right + 8 : nr.left - 8) - fr.left;
const x2 = (left ? pr.left - 4 : pr.right + 4) - fr.left;
const yy = y - fr.top;
svgEl(svg, 'path', { d: `M${x1.toFixed(1)} ${yy.toFixed(1)}H${x2.toFixed(1)}` });
svgEl(svg, 'circle', { cx: x2.toFixed(1), cy: yy.toFixed(1), r: '2.4' });
}
};
}
/* ------------------------------------------------------------------ the story */
/** The phone at story position P, from 0 to 6 in chapters; t is how far into its chapter. */
function storyState(ph, P) {
const s = blank();
P = clamp(P, 0, STORY_END - 0.0001);
const ch = Math.floor(P);
const t = P - ch;
const F = s.finger;
const g = ph.g;
const inward = ph.lefty ? 1 : -1;
const C = L('C'), D = L('D'), G = L('G'), N = L('N'), S = L('S'), Z = LETTERS.length - 1;
const messages = clamp(LIST_TOP + g.rowTop.Messages - 250, 0, g.maxScroll); // Messages' row at y 250, above the letters
switch (ch) {
case 0: // One column, A to Z
F.x = 195;
F.y = lerp(790, 470, E(t, 0.1, 0.4));
F.o = seg(t, 0.02, 0.1) * (1 - seg(t, 0.4, 0.48));
F.press = t > 0.1 && t < 0.4 ? 1 : 0;
s.drawer = E(t, 0.12, 0.42);
s.list = E(t, 0.52, 0.85) * messages;
break;
case 1: // Slide along the letters: N to Z, Z to C. N, not M: resting on M would land Messages
// at the thumb's height, under the bubble; N's landing keeps the list where chapter 1 left it.
s.drawer = 1;
s.scrub = keys(t, [[0.15, N], [0.45, Z], [0.52, Z], [0.85, C]]);
s.press = seg(t, 0.08, 0.14) * (1 - seg(t, 0.9, 0.97));
s.list = lerp(messages, ph.scrollAt(s.scrub), E(t, 0.06, 0.16));
F.x = g.alphaX;
F.y = ph.letterYAt(s.scrub);
F.o = seg(t, 0.04, 0.1) * (1 - seg(t, 0.9, 0.97));
F.press = s.press > 0.5 ? 1 : 0;
s.marks.spacing = seg(t, 0.16, 0.2) * (1 - seg(t, 0.46, 0.5));
s.marks.inset = seg(t, 0.56, 0.6) * (1 - seg(t, 0.92, 0.97));
break;
case 2: // Where the letter lands: C to S, held
s.drawer = 1;
s.scrub = keys(t, [[0.12, C], [0.3, S]]);
s.press = seg(t, 0.06, 0.12) * (1 - seg(t, 0.9, 0.96));
s.list = ph.scrollAt(s.scrub);
F.x = g.alphaX;
F.y = ph.letterYAt(s.scrub);
F.o = seg(t, 0.02, 0.08) * (1 - seg(t, 0.9, 0.96));
F.press = s.press > 0.5 ? 1 : 0;
s.marks.middle = seg(t, 0.36, 0.42) * (1 - seg(t, 0.9, 0.96));
s.marks.thumb = seg(t, 0.46, 0.52) * (1 - seg(t, 0.9, 0.96));
break;
case 3: // Straight from the home screen: the band, D to S to G
s.drawer = Math.max(1 - E(t, 0, 0.14), E(t, 0.3, 0.335)); // closes, then opens in "120 ms"
s.scrub = keys(t, [[0.3, D], [0.6, S], [0.62, S], [0.8, G]]);
s.list = t < 0.14 ? ph.scrollFor(S) : ph.scrollAt(s.scrub);
s.press = seg(t, 0.3, 0.32) * (1 - seg(t, 0.86, 0.92));
s.scrubX = g.alphaX - 12 * inward; // on the 40 dp band, x 372 (left-handed 18)
F.x = s.scrubX;
F.y = ph.letterYAt(s.scrub);
F.o = seg(t, 0.22, 0.27) * (1 - seg(t, 0.86, 0.92));
F.press = t > 0.27 && t < 0.88 ? 1 : 0;
s.marks.band = seg(t, 0.16, 0.2) * (1 - seg(t, 0.62, 0.66));
break;
case 4: { // A page that isn't there
s.drawer = 1 - E(t, 0, 0.12);
s.list = ph.scrollFor(G);
s.page = E(t, 0.18, 0.34);
s.quickSide = 'right';
F.y = 430;
if (t < 0.37) {
F.x = lerp(300, 90, E(t, 0.16, 0.34));
F.o = seg(t, 0.13, 0.17) * (1 - seg(t, 0.34, 0.37));
F.press = t > 0.16 && t < 0.34 ? 1 : 0;
} else {
F.x = lerp(330, 330 - 0.55 * W, E(t, 0.42, 0.72));
F.o = seg(t, 0.37, 0.41) * (1 - seg(t, 0.72, 0.76));
F.press = t > 0.41 && t < 0.72 ? 1 : 0;
}
const pulled = 0.55 * E(t, 0.42, 0.72);
s.quick = pulled + (1 - pulled) * outCubic(seg(t, 0.72, 0.8));
s.marks.threshold = seg(t, 0.44, 0.48) * (1 - seg(t, 0.8, 0.84));
break;
}
default: { // 5: No opening animation
const back = t >= 0.82;
s.page = 1;
s.quickSide = 'right';
s.quick = back ? 0 : 1;
s.app = t >= 0.1 && !back ? 1 : 0;
F.x = 195;
F.y = lerp(830, 600, E(t, 0.7, 0.8));
F.o = seg(t, 0.66, 0.7) * (1 - seg(t, 0.8, 0.84));
F.press = t > 0.7 && t < 0.8 ? 1 : 0;
}
}
return s;
}
/**
* The story phone follows the scroll position. P comes from each chapter's own box, so chapters
* can differ in height, and the gap before the black band holds chapter 4's last frame.
*/
function setupStory(ph) {
const root = document.querySelector('[data-story]');
const stage = root && root.querySelector('.story__stage');
const steps = root ? [...root.querySelectorAll('[data-step]')] : [];
if (!stage || !steps.length) return null;
const night = document.getElementById('past-the-last-page');
const narrow = window.matchMedia('(max-width: 699px)');
let lastP = -1;
return function update(force) {
const vh = window.innerHeight;
const st = stage.getBoundingClientRect();
const line = narrow.matches ? st.bottom + (vh - st.bottom) * 0.25 : vh / 2; // the reading line
let P = steps.length - 0.0001;
for (let i = 0; i < steps.length; i++) {
const rc = steps[i].getBoundingClientRect();
if (line < rc.top) {
P = Math.max(0, i - 0.0001);
break;
}
if (line < rc.bottom) {
P = i + (line - rc.top) / rc.height;
break;
}
}
const ch = Math.min(STORY_END - 1, Math.floor(P));
const shown = reduced ? ch + REST[ch] : P;
if (force || Math.abs(shown - lastP) > 0.0002) {
lastP = shown;
ph.render(storyState(ph, shown));
}
if (narrow.matches && night) { // the sticky phone's background follows the black band's edges
const nr = night.getBoundingClientRect();
stage.style.setProperty('--night-from', `${clamp(nr.top - st.top, 0, st.height).toFixed(1)}px`);
stage.style.setProperty('--night-to', `${clamp(nr.bottom - st.top, 0, st.height).toFixed(1)}px`);
}
};
}
/* ------------------------------------------------------------------ the playground */
/**
* A phone that answers to touch and mouse.
* opts.caption element that narrates what happened (optional)
* opts.demos element holding [data-demo] buttons (optional)
* opts.locked the app list stays open: no home screen, menus or closing (the timed test)
* opts.onRowTap called with an app's name when its row in the list is tapped
* opts.keyboard a slider over the alphabet, for the keyboard and screen readers
* opts.armable on a touch screen, the page scrolls over the phone until the phone is tapped
*/
function setupPlay(ph, opts = {}) {
const s = blank();
if (opts.locked) s.drawer = 1;
const caption = opts.caption || null;
const HELLO = 'Swipe up on the home screen to open the list.';
const HOME_AGAIN = 'Home. Swiping up from the bottom edge works from anywhere.';
const opened = () => `Every app, A to Z. Now drag along the letters on the ${look.lefty ? 'left' : 'right'}.`;
const landedOn = (stop) => (stop <= 0 ? 'The magnifier takes the list back to the search field.' : `Landed on ${LETTERS[stop - 1]}.`);
const say = (text) => {
if (caption && caption.textContent !== text) caption.textContent = text;
};
// A tiny tween engine over paths into the state ("drawer", "finger.x", "hidden.Podcasts").
let anims = [];
let raf = 0;
let token = 0;
let scrubbing = false;
let listTarget = null;
let snackTimer = 0;
let lastHidden = null;
let lastTick = -1;
let lastStop = 0; // the slider's value: 0 the magnifier, 1 to 17 the letters
let gest = null;
let keyTimer = 0;
const getp = (p) => p.split('.').reduce((o, k) => (o == null ? undefined : o[k]), s);
const setp = (p, v) => {
const ks = p.split('.');
let o = s;
for (let i = 0; i < ks.length - 1; i++) o = o[ks[i]];
o[ks[ks.length - 1]] = v;
};
function derive() {
let more = false;
if (scrubbing) {
if (!gest) { // demos and keys: the finger dot on the letters
s.finger.x = s.scrubX == null ? ph.g.alphaX : s.scrubX;
s.finger.y = ph.letterYAt(s.scrub);
}
listTarget = ph.scrollFor(s.scrub);
const tick = Math.round(s.scrub);
if (tick !== lastTick) {
if (gest && gest.mode === 'scrub') buzz();
lastTick = tick;
}
}
if (listTarget != null) {
const d = listTarget - s.list;
if (Math.abs(d) < 0.5) {
s.list = listTarget;
listTarget = null;
} else {
s.list += d * 0.32;
more = true;
}
}
return more;
}
function frame(now) {
raf = 0;
anims = anims.filter((a) => {
const k = a.dur ? clamp((now - a.start) / a.dur) : 1;
setp(a.key, lerp(a.from, a.to, a.ease(k)));
if (k >= 1) {
a.done();
return false;
}
return true;
});
const more = derive();
ph.render(s);
if (anims.length || more) raf = requestAnimationFrame(frame);
}
const kick = () => {
if (!raf) raf = requestAnimationFrame(frame);
};
const drop = (key) => {
anims = anims.filter((a) => {
if (a.key !== key) return true;
a.done();
return false;
});
};
function to(patch, dur = 320, ease = inOut) {
const start = performance.now();
const all = Object.entries(patch).map(([key, v]) => new Promise((done) => {
drop(key);
anims.push({ key, from: +getp(key) || 0, to: v, start, dur: reduced ? 0 : dur, ease, done });
}));
kick();
return Promise.all(all);
}
function set(patch) {
for (const [key, v] of Object.entries(patch)) {
drop(key);
setp(key, v);
}
kick();
}
const wait = (ms) => new Promise((r) => setTimeout(r, reduced ? 0 : ms));
const stopAll = () => {
token++;
anims.forEach((a) => a.done());
anims = [];
scrubbing = false;
};
// The alphabet as a slider, for the keyboard and screen readers.
let slider = null;
function syncSlider() {
if (!slider) return;
slider.setAttribute('aria-valuenow', String(lastStop));
slider.setAttribute('aria-valuetext', lastStop <= 0 ? 'Search' : LETTERS[lastStop - 1]);
}
/** A scrub from the keys is still showing: it ends now, as a pointer or a demo takes over. */
function endKeys() {
if (!keyTimer) return;
clearTimeout(keyTimer);
keyTimer = 0;
scrubbing = false;
to({ press: 0 }, PRESS_OUT_MS, outCubic);
}
// Building blocks shared by gestures and the demo buttons.
const fingerAt = (x, y) => set({ 'finger.x': x, 'finger.y': y });
const fingerOff = () => to({ 'finger.o': 0, 'finger.press': 0, 'finger.ring': 0 }, 220);
async function closeAll() {
s.held = null;
scrubbing = false;
set({ app: 0 });
await to({ drawer: 0, folder: 0, quick: 0, menu: 0, sheet: 0, press: 0, pull: 0, page: 0, snack: 0, menuPick: 0 }, 280);
}
const openDrawer = () => to({ drawer: 1 }, 300).then(() => say(opened()));
const closeDrawer = () => to({ drawer: 0, menu: 0, press: 0 }, 260).then(() => { s.held = null; });
function openFolder(id) {
s.folderId = id;
say('A folder the way 0.16.0 opens it, with its apps at the bottom in your home screen’s columns. Tap above them to close it.');
return to({ folder: 1 }, 300, outCubic);
}
const closeFolder = () => to({ folder: 0 }, 240);
function openMenu(name) {
s.held = name;
const ry = ph.rowY(name, s.list);
const below = ry + 34;
s.menuY = below + ph.g.menuH > H - 70 ? ry - 34 - ph.g.menuH : below;
say(`Tap Hide app to hide ${name}.`);
return to({ menu: 1, 'finger.ring': 0 }, 200, outCubic);
}
async function hideApp(name) {
if (!name) return;
set({ menuPick: 1 });
await wait(120);
await to({ menu: 0 }, 180);
s.held = null;
s.menuPick = 0;
s.snackText = `${name} is hidden`;
lastHidden = name;
await to({ [`hidden.${name}`]: 1, snack: 1 }, 380);
ph.measure();
say(`${name} is hidden from the list and from search. Tap Undo to bring it back.`);
clearTimeout(snackTimer);
snackTimer = setTimeout(() => to({ snack: 0 }, 260), 4200);
}
async function unhide(name) {
if (!name) return;
clearTimeout(snackTimer);
await to({ [`hidden.${name}`]: 0, snack: 0 }, 320);
ph.measure();
say(`${name} is back.`);
}
/** The finger slides along the letters from one to another; x is where it is across, if not on the letters. */
async function sweep(from, target, dur, x = null) {
scrubbing = true;
s.scrubX = x;
s.scrub = from;
await to({ scrub: target }, dur, inOut);
scrubbing = false;
}
// The demo buttons.
const demos = {
async drawer(alive) {
await closeAll();
if (!alive()) return;
fingerAt(195, 790);
await to({ 'finger.o': 1 }, 160);
set({ 'finger.press': 1 });
await to({ 'finger.y': 470, drawer: 1 }, 650);
set({ 'finger.press': 0 });
await fingerOff();
if (alive()) say(opened());
},
async scrub(alive) {
if (s.drawer < 0.99 || s.folder > 0.01 || s.quick > 0.01 || s.app) {
await demos.drawer(alive);
if (!alive()) return;
}
const start = L('B');
s.scrubX = null;
s.scrub = start;
fingerAt(ph.g.alphaX, ph.letterYAt(start));
await to({ 'finger.o': 1, press: 1 }, PRESS_IN_MS, outCubic);
set({ 'finger.press': 1 });
if (!alive()) return;
await sweep(start, LETTERS.length - 1, 1500);
if (!alive()) return;
await sweep(LETTERS.length - 1, L('F'), 900);
set({ 'finger.press': 0 });
await to({ press: 0, 'finger.o': 0 }, PRESS_OUT_MS, outCubic);
if (!alive()) return;
lastStop = L('F') + 1;
syncSlider();
say(landedOn(lastStop));
},
async quick(alive) {
await closeAll();
if (!alive()) return;
// To the second page, which is the last.
fingerAt(300, 430);
await to({ 'finger.o': 1 }, 160);
set({ 'finger.press': 1 });
await to({ 'finger.x': 90, page: 1 }, 420);
set({ 'finger.press': 0 });
await to({ 'finger.o': 0 }, 140);
if (!alive()) return;
// A new touch, and on past the last page: the black page follows the finger.
s.quickSide = 'right';
fingerAt(330, 430);
await to({ 'finger.o': 1 }, 140);
if (!alive()) return;
set({ 'finger.press': 1 });
const crossing = setTimeout(() => { if (alive()) buzz(); }, reduced ? 0 : (520 * OPEN_DISTANCE) / 0.55);
await to({ 'finger.x': 330 - 0.55 * W, quick: 0.55 }, 520, linear);
if (!alive()) {
clearTimeout(crossing);
return;
}
set({ 'finger.press': 0 });
fingerOff();
await to({ quick: 1 }, 200, outCubic);
if (!alive()) return;
set({ app: 1 });
say('Past the last page: the black page, then the app, with no zoom. Swipe up from the bottom edge to go back.');
},
/** On the home screen, down along the edge where the alphabet lives: the list opens at the letter. */
async edge(alive) {
await closeAll();
if (!alive()) return;
const x = ph.lefty ? 18 : W - 18; // inside the home screen's band
const from = L('C');
const target = L('G');
const y0 = ph.letterYAt(from);
fingerAt(x, y0 - 14);
await to({ 'finger.o': 1 }, 160);
if (!alive()) return;
set({ 'finger.press': 1 });
await to({ 'finger.y': y0 }, 90, linear); // the first few dp down the edge are what start it
if (!alive()) return;
s.scrubX = x;
s.scrub = from;
s.list = ph.scrollFor(from);
scrubbing = true;
to({ drawer: 1 }, OPEN_FROM_SCRUB_MS, outCubic);
await to({ press: 1 }, PRESS_IN_MS, outCubic);
if (!alive()) return;
await sweep(from, target, 760, x);
if (!alive()) return;
set({ 'finger.press': 0 });
await to({ press: 0, 'finger.o': 0 }, PRESS_OUT_MS, outCubic);
if (!alive()) return;
lastStop = target + 1;
syncSlider();
say(`Landed on ${LETTERS[target]}, straight from the home screen.`);
},
async reset() {
await closeAll();
for (const name of Object.keys(s.hidden)) s.hidden[name] = 0;
set({ align: 0, size: 1, weight: DEFAULT_WEIGHT, list: 0, app: 0, quick: 0 });
ph.render(s);
ph.measure();
lastStop = 0;
syncSlider();
say(HELLO);
},
};
for (const btn of opts.demos ? opts.demos.querySelectorAll('[data-demo]') : []) {
btn.addEventListener('click', () => {
stopAll();
endKeys();
const mine = token;
const run = demos[btn.dataset.demo];
if (run) run(() => mine === token);
});
}
if (opts.keyboard) {
slider = document.createElement('div');
slider.className = 'strip-a11y';
slider.tabIndex = 0;
slider.setAttribute('role', 'slider');
slider.setAttribute('aria-label', 'Alphabet');
slider.setAttribute('aria-valuemin', '0');
slider.setAttribute('aria-valuemax', String(LETTERS.length));
ph.host.appendChild(slider);
syncSlider();
slider.addEventListener('keydown', (e) => {
let stop = lastStop;
switch (e.key) {
case 'ArrowUp': case 'ArrowLeft': stop -= 1; break;
case 'ArrowDown': case 'ArrowRight': stop += 1; break;
case 'Home': stop = 0; break;
case 'End': stop = LETTERS.length; break;
default: return;
}
e.preventDefault();
token++; // a running demo stops here
stop = clamp(stop, 0, LETTERS.length);
s.held = null;
set({ app: 0 });
if (s.folder > 0 || s.quick > 0 || s.menu > 0 || s.sheet > 0) to({ folder: 0, quick: 0, menu: 0, sheet: 0 }, OPEN_FROM_SCRUB_MS);
if (s.drawer < 1) to({ drawer: 1 }, OPEN_FROM_SCRUB_MS, outCubic);
scrubbing = true;
s.scrubX = null;
s.scrub = stop - 1;
lastStop = stop;
syncSlider();
to({ press: 1 }, PRESS_IN_MS, outCubic);
buzz();
clearTimeout(keyTimer);
keyTimer = setTimeout(() => {
keyTimer = 0;
scrubbing = false;
to({ press: 0 }, PRESS_OUT_MS, outCubic);
say(landedOn(lastStop));
}, 600);
});
}
// Gestures on the phone itself.
const scr = ph.screen;
let lpTimer = 0;
let holdTimer = 0;
let backTimer = 0;
const pt = (e) => {
const rc = scr.getBoundingClientRect();
return { x: (e.clientX - rc.left) / ph.scale, y: (e.clientY - rc.top) / ph.scale };
};
/** The finger's speed across, in dp per second (rightward positive), over its last 80 ms. */
function velocity(g) {
const now = performance.now();
const recent = g.samples.filter((p) => now - p.t <= 80);
if (recent.length < 2) return 0;
const a = recent[0];
const b = recent[recent.length - 1];
return b.t > a.t ? ((b.x - a.x) * 1000) / (b.t - a.t) : 0;
}
const cancelHold = () => {
clearTimeout(lpTimer);
lpTimer = 0;
if (gest && !gest.held) {
drop('finger.ring');
s.finger.ring = 0;
if (s.menu < 0.5) s.held = null;
}
};
function bounce(el) {
el.classList.remove('tap');
void el.offsetWidth;
el.classList.add('tap');
}
/** The finger takes the alphabet: in the open list, from the home screen's edge, or after a hold. */
function beginScrub(g, p, via) {
g.mode = 'scrub';
g.via = via;
g.scrubT0 = performance.now();
scrubbing = true;
s.scrubX = p.x;
s.scrub = ph.letterAtY(p.y);
lastTick = Math.round(s.scrub);
if (via !== 'list') { // the list opens already at the letter
listTarget = null;
s.list = ph.scrollFor(s.scrub);
}
to({ press: 1 }, PRESS_IN_MS, outCubic);
}
function endScrub(g) {
scrubbing = false;
to({ press: 0 }, PRESS_OUT_MS, outCubic);
if ((g.via === 'edge' || g.via === 'hold') && performance.now() - g.scrubT0 < MIN_SCRUB_MS) {
// A flick, not a scrub: the plain list from the top.
listTarget = null;
to({ list: 0 }, 280);
lastStop = 0;
syncSlider();
say('That was a flick, so the list opened at the top. Rest your thumb a moment longer to pick a letter.');
return;
}
listTarget = ph.scrollFor(s.scrub); // the list lands on the last letter, however short the scrub
lastStop = clamp(Math.round(s.scrub), -1, LETTERS.length - 1) + 1;
syncSlider();
if (g.via === 'hold') say('Swipe up and hold works from anywhere on the home screen. The further your thumb is from the edge, the further the letters reach out to it.');
else if (lastStop === 0) say(landedOn(0));
else if (g.via === 'edge') say(`Landed on ${LETTERS[lastStop - 1]}, straight from the home screen.`);
else say(landedOn(lastStop));
}
/** Swipe up and hold: still for a moment after the swipe, the touch carries on as the alphabet. */
function holdFired() {
holdTimer = 0;
if (!gest || gest.mode !== 'home' || gest.dir !== 'v') return;
to({ drawer: 1 }, OPEN_FROM_SCRUB_MS, outCubic);
beginScrub(gest, { x: gest.x, y: gest.y }, 'hold');
}
scr.addEventListener('pointerdown', (e) => {
if (e.button > 0) return;
stopAll();
endKeys();
if (s.press > 0) to({ press: 0 }, PRESS_OUT_MS, outCubic); // a wave stopped half-way goes back
clearTimeout(holdTimer);
clearTimeout(backTimer);
const p = pt(e);
try {
scr.setPointerCapture(e.pointerId);
} catch (_) { /* not every pointer can be captured */ }
const now = performance.now();
gest = { x0: p.x, y0: p.y, x: p.x, y: p.y, t0: now, mode: 'home', target: e.target, moved: false, dir: null, held: false, samples: [{ t: now, x: p.x }] };
set({ 'finger.x': p.x, 'finger.y': p.y, 'finger.o': 0.9, 'finger.press': 1, 'finger.ring': 0 });
const st = ph.g.strip;
const onStripY = p.y > st.top - 16 && p.y < st.bottom + 16;
if (e.target.closest('.snack__undo') && s.snack > 0.5) gest.mode = 'undo';
else if (p.y > H - 44 && !opts.locked) gest.mode = 'edge';
else if (s.app) gest.mode = 'app';
else if (s.menu > 0.5) gest.mode = 'menu';
else if (s.sheet > 0.5) gest.mode = 'sheet';
else if (s.folder > 0.5) gest.mode = 'folder';
else if (s.drawer > 0.5) {
const onBand = (ph.lefty ? p.x < TOUCH_W : p.x > W - TOUCH_W) && onStripY;
if (onBand) {
const onBack = ph.lefty ? p.x < BACK_ZONE : p.x > W - BACK_ZONE;
if (onBack && !opts.locked) {
// Android's Back strip: a sideways swipe here is still Back. A slide or a rest is a scrub.
gest.mode = 'strip-wait';
const mine = gest;
backTimer = setTimeout(() => {
if (gest !== mine || mine.mode !== 'strip-wait') return;
beginScrub(mine, { x: mine.x, y: mine.y }, 'list');
kick();
}, REST_BEFORE_SCRUB_MS);
} else {
beginScrub(gest, p, 'list');
}
} else {
gest.mode = 'list';
gest.list0 = s.list;
listTarget = null;
const row = e.target.closest('.row');
gest.row = row ? row.dataset.row : null;
if (gest.row && !opts.locked) {
to({ 'finger.ring': 1 }, 450, linear);
lpTimer = setTimeout(() => {
if (!gest || gest.moved) return;
gest.held = true;
openMenu(gest.row);
}, 450);
}
}
} else {
// The home screen. Its edge, where the alphabet lives, may turn into a scrub.
gest.edge = (ph.lefty ? p.x < HOME_TOUCH_W : p.x > W - HOME_TOUCH_W) && onStripY;
const cell = e.target.closest('[data-key]');
if (cell && cell.dataset.key === 'clock') {
to({ 'finger.ring': 1 }, 450, linear);
lpTimer = setTimeout(() => {
if (!gest || gest.moved) return;
gest.held = true;
set({ 'finger.ring': 0 });
say('The clock’s options. Tap above the sheet to close it.');
to({ sheet: 1 }, 360, outCubic);
}, 450);
}
}
});
scr.addEventListener('pointermove', (e) => {
if (!gest) return;
const p = pt(e);
gest.x = p.x;
gest.y = p.y;
gest.samples.push({ t: performance.now(), x: p.x });
if (gest.samples.length > 24) gest.samples.shift();
const dx = p.x - gest.x0;
const dy = p.y - gest.y0;
const ax = Math.abs(dx);
const ay = Math.abs(dy);
if (!gest.moved && Math.hypot(dx, dy) > 9) {
gest.moved = true;
if (!gest.held) cancelHold();
}
s.finger.x = p.x;
s.finger.y = p.y;
switch (gest.mode) {
case 'strip-wait':
if (ay > 8 && ay >= ax) {
clearTimeout(backTimer);
beginScrub(gest, p, 'list');
} else if (ax > 8) {
clearTimeout(backTimer);
gest.mode = 'back';
}
break;
case 'scrub':
s.scrubX = p.x;
s.scrub = ph.letterAtY(p.y);
break;
case 'list':
if (gest.moved && !gest.held) {
if (gest.list0 <= 1 && dy > 0 && !opts.locked) s.drawer = clamp(1 - dy / 320);
else s.list = clamp(gest.list0 - dy, 0, ph.g.maxScroll);
}
break;
case 'home':
if (gest.held) break;
if (gest.edge) {
if (ay > 8 && ay > 2 * ax) { // up or down along the edge: the list opens under the thumb
gest.edge = false;
to({ drawer: 1 }, OPEN_FROM_SCRUB_MS, outCubic);
beginScrub(gest, p, 'edge');
break;
}
if (ax > 8 && ax >= ay) gest.edge = false; // sideways: a page swipe after all
else if (!gest.moved) break;
else gest.edge = false; // slanted: an ordinary swipe
}
if (!gest.dir && gest.moved) gest.dir = ay > ax ? 'v' : 'h';
if (gest.dir === 'v') {
s.drawer = clamp(-dy / 280);
if (-dy >= HOLD_MIN_SWIPE && (!gest.holdAt || Math.hypot(p.x - gest.holdAt.x, p.y - gest.holdAt.y) > 3)) {
gest.holdAt = { x: p.x, y: p.y };
clearTimeout(holdTimer);
holdTimer = setTimeout(holdFired, HOLD_STILL_MS);
}
} else if (gest.dir === 'h') {
const last = s.page > HOME.length - 1.5;
if (s.page < 0.5 && dx > 0) { // before the first page: only a stretch here
s.pull = rubber(dx);
s.quick = 0;
} else if (last && dx < 0) { // past the last page: quick launch
const q = clamp(-dx / W);
if ((q >= OPEN_DISTANCE) !== (s.quick >= OPEN_DISTANCE)) buzz();
s.quick = q;
s.quickSide = 'right';
s.pull = 0;
} else {
s.pull = dx;
s.quick = 0;
}
}
break;
default:
break;
}
kick();
});
const end = (e) => {
if (!gest) return;
clearTimeout(lpTimer);
clearTimeout(holdTimer);
clearTimeout(backTimer);
const g = gest;
gest = null;
const dx = g.x - g.x0;
const dy = g.y - g.y0;
const tap = !g.moved && performance.now() - g.t0 < 450;
if (!(g.mode === 'list' && g.held)) to({ 'finger.ring': 0 }, 120);
to({ 'finger.o': 0, 'finger.press': 0 }, 240);
if (e.type === 'pointercancel') {
if (g.mode === 'scrub') {
scrubbing = false;
to({ press: 0 }, PRESS_OUT_MS, outCubic);
}
to({ pull: 0, drawer: Math.round(s.drawer), quick: 0 }, 200);
return;
}
const mine = token;
switch (g.mode) {
case 'undo':
unhide(lastHidden);
break;
case 'edge':
if (dy < -36) closeAll().then(() => say(HOME_AGAIN));
break;
case 'app':
if (dy < -60) {
set({ app: 0, quick: 0 });
say(HOME_AGAIN);
} else if (tap && g.target.closest('.cam__shutter')) {
set({ shutter: 1 });
setTimeout(() => set({ shutter: 0 }), 140);
}
break;
case 'menu':
if (tap && g.target.closest('.mi--hide')) hideApp(s.held);
else {
s.held = null;
to({ menu: 0 }, 180);
}
break;
case 'sheet': {
const spanEl = g.target.closest('.seg span');
if (tap && spanEl && spanEl.dataset.v !== undefined) {
const v = +spanEl.dataset.v;
const which = spanEl.parentElement.dataset.seg;
if (which === 'align') to({ align: v }, 380);
else if (which === 'size') to({ size: v }, 380);
else to({ weight: v }, 420);
} else if (tap && !g.target.closest('.sheet')) to({ sheet: 0 }, 300);
else if (dy > 60) to({ sheet: 0 }, 300);
break;
}
case 'folder':
if (tap) {
const app = g.target.closest('.ffolder__app');
if (app) bounce(app);
else if (g.y0 < ph.folderTop) closeFolder();
}
break;
case 'strip-wait': { // let go without moving: that letter, with the wave in and out once
beginScrub(g, { x: g.x0, y: g.y0 }, 'list');
listTarget = ph.scrollFor(s.scrub);
setTimeout(() => { if (mine === token) endScrub(g); }, reduced ? 0 : PRESS_IN_MS);
break;
}
case 'back':
closeDrawer().then(() => say('That was Back. A sideways swipe from the edge is still Back, even over the letters.'));
break;
case 'scrub':
endScrub(g);
break;
case 'list':
if (g.held) break; // the menu stays open
if (s.drawer < 1) {
if (s.drawer < 0.75) closeDrawer().then(() => say('Closed. Swipe up to open it again.'));
else to({ drawer: 1 }, 200);
} else if (tap && g.row) {
const row = ph.r.rows.get(g.row);
row.classList.add('flash');
setTimeout(() => row.classList.remove('flash'), 220);
if (opts.onRowTap) opts.onRowTap(g.row, row);
else say(`On a phone, ${g.row} would open now. Hold it to see its menu.`);
}
break;
case 'home':
if (g.held) break;
if (g.dir === 'v') {
if (s.drawer > 0.3) openDrawer();
else to({ drawer: 0 }, 220);
} else if (g.dir === 'h') {
if (s.quick > 0) {
// Past the last page (QuickLaunch, QuickLaunchPage.settle).
const v = velocity(g);
const open = (-v >= FLICK_SPEED && s.quick >= FLICK_DISTANCE) || (v < FLICK_SPEED && s.quick >= OPEN_DISTANCE);
if (open && s.quick < OPEN_DISTANCE) buzz();
const target = open ? 1 : 0;
const speed = Math.max(0, open ? -v : v);
const ms = clamp((2000 * Math.abs(target - s.quick) * W) / Math.max(speed, MIN_SETTLE_SPEED), MIN_SETTLE_MS, MAX_SETTLE_MS);
to({ quick: target }, ms, outCubic).then(() => {
if (mine !== token) return;
if (open) {
set({ app: 1 });
say('Past the last page: the black page, then the app, with no zoom. Swipe up from the bottom edge to go back.');
} else {
say('You let go before the line, so the home screen came back.');
}
});
} else if (s.page < 0.5 && dx > 0) {
to({ pull: 0 }, 260, outCubic);
say('Nothing is set for this end in the drawing, so it only stretches. Try past the last page.');
} else if (s.page < 0.5 && dx < -70) {
to({ page: 1, pull: 0 }, 380).then(() => { if (mine === token) say('This is the last page. Keep swiping left.'); });
} else if (s.page > 0.5 && dx > 70) {
to({ page: 0, pull: 0 }, 380).then(() => { if (mine === token) say(HELLO); });
} else {
to({ pull: 0 }, 260, outCubic);
}
} else if (tap) {
const cell = g.target.closest('[data-key]');
if (cell && cell.dataset.folder) openFolder(cell.dataset.folder);
else if (cell && cell.classList.contains('cell')) {
bounce(cell);
say('Swipe up anywhere on the home screen to see every app.');
}
}
break;
default:
break;
}
kick();
};
scr.addEventListener('pointerup', end);
scr.addEventListener('pointercancel', end);
scr.addEventListener('contextmenu', (e) => e.preventDefault());
// On a touch screen the phone starts out letting the page scroll over it (touch-action: pan-y),
// so a thumb scrolling down the page isn't caught by the drawing. A finished touch on it, a tap
// or a sideways swipe, hands it every gesture; it lets go again once it is off the screen.
if (opts.armable) {
const host = ph.host;
host.classList.add('is-armable');
const hint = document.createElement('p');
hint.className = 'arm-hint';
hint.setAttribute('aria-hidden', 'true');
hint.textContent = 'Tap to try it';
host.appendChild(hint);
scr.addEventListener('pointerup', (e) => {
if (e.pointerType === 'touch') host.classList.add('is-armed');
});
if ('IntersectionObserver' in window) {
new IntersectionObserver((seen) => {
if (!seen[seen.length - 1].isIntersecting) host.classList.remove('is-armed');
}).observe(host);
}
}
ph.render(s);
return {
render: () => ph.render(s),
/** Back to a fresh start; for the timed test, the list at its top. */
reset() {
stopAll();
endKeys();
Object.assign(s, blank(), { drawer: opts.locked ? 1 : 0 });
listTarget = null;
ph.render(s);
},
say,
};
}
/* ------------------------------------------------------------------ the two settings */
function setupLook(phones, rerender, say) {
function sync() {
document.querySelectorAll('[data-look="lefty"]').forEach((b) => b.setAttribute('aria-checked', String(look.lefty)));
document.querySelectorAll('[data-look="comfy"]').forEach((b) => b.setAttribute('aria-pressed', String((b.dataset.v === '1') === look.comfy)));
}
document.addEventListener('click', (e) => {
const b = e.target.closest('[data-look]');
if (!b) return;
let message;
if (b.dataset.look === 'lefty') {
look.lefty = !look.lefty;
message = look.lefty ? 'The alphabet is on the left edge now.' : 'The alphabet is back on the right.';
} else if (b.dataset.look === 'comfy') {
const comfy = b.dataset.v === '1';
if (comfy === look.comfy) return;
look.comfy = comfy;
message = look.comfy ? 'Comfy rows.' : 'Compact rows.';
} else {
return;
}
Object.values(phones).forEach((p) => p.setLook(look));
rerender();
sync();
say(message);
});
sync();
}
/* ------------------------------------------------------------------ a grid against the list */
/** Round one's phone: the same 40 apps in a grid drawer, sorted A to Z as Lawnchair's is. */
function gridMarkup(apps) {
return `<div class="phone" aria-hidden="true"><div class="screen"><div class="world"><div class="wall"></div></div>
<div class="rgrid">${apps.map((a) => `<button type="button" class="rcell" data-app="${a.n}" tabindex="-1">${icon(a)}<span>${a.n}</span></button>`).join('')}</div>
<div class="sbar"><span class="sbar__time">9:41</span><span class="sbar__icons"><span class="sbar__sig"><i></i><i></i><i></i><i></i></span><span class="sbar__bat"></span></span></div>
<i class="notch"></i><i class="gbar"></i></div></div>`;
}
function setupRace(listPhone) {
const $ = (sel) => document.querySelector(sel);
const stage = $('[data-race-stage]');
const gridHost = $('[data-race-grid]');
const pillEl = $('[data-race-pill]');
const t1El = $('[data-race-t1]');
const t2El = $('[data-race-t2]');
const verdict = $('[data-race-verdict]');
const startBtn = $('[data-race-start]');
const roundEl = $('[data-race-round]');
const msgEl = $('[data-race-msg]');
if (!stage || !gridHost || !listPhone || !pillEl || !t1El || !t2El || !verdict || !startBtn || !roundEl || !msgEl) return null;
// Only apps that are neither on the home screen nor in a folder.
const TARGETS = ['Radio', 'Measure', 'Vault', 'Stocks', 'Tasks', 'Compass', 'Lens', 'Health', 'Docs', 'Games', 'Alarm'];
let phase = 'idle';
let target = 'Radio';
let lastTarget = null;
let t0 = 0;
let t1 = 0;
let raf = 0;
let run = 0;
let gridPhone = null;
const fmt = (ms) => `${(ms / 1000).toFixed(2)} s`;
const label = (text) => { startBtn.textContent = text; };
function fitGrid() {
const w = gridHost.clientWidth;
if (w && gridPhone) gridPhone.style.setProperty('--s', (w / 414).toFixed(5));
}
function buildGrid() {
gridHost.innerHTML = gridMarkup(APPS);
gridPhone = gridHost.querySelector('.phone');
const time = document.querySelector('.sbar__time');
gridHost.querySelector('.sbar__time').textContent = time ? time.textContent : '9:41';
fitGrid();
}
if ('ResizeObserver' in window) new ResizeObserver(fitGrid).observe(gridHost);
const list = setupPlay(listPhone, { locked: true, onRowTap: (name, row) => tappedRow(name, row) });
function setPhase(p) {
phase = p;
stage.dataset.phase = p;
}
function tick(now) {
raf = 0;
if (phase === 'r1') t1El.textContent = fmt(now - t0);
else if (phase === 'r2') t2El.textContent = fmt(now - t0);
else return;
raf = requestAnimationFrame(tick);
}
function shake(el) {
el.classList.remove('miss');
void el.offsetWidth;
el.classList.add('miss');
buzz(30);
}
function start() {
cancelAnimationFrame(raf);
run++;
do target = TARGETS[(Math.random() * TARGETS.length) | 0]; while (target === lastTarget);
lastTarget = target;
pillEl.textContent = target;
t1El.textContent = '–';
t2El.textContent = '–';
buildGrid();
list.reset();
verdict.textContent = `Round 1: find ${target} in the grid.`;
label('Start again');
// The clock only starts once the whole phone is on screen (on phones it sits below the button).
const rc = stage.getBoundingClientRect();
const visible = rc.top >= 0 && rc.bottom <= window.innerHeight;
if (!visible) stage.scrollIntoView({ block: 'center', behavior: 'instant' });
setPhase('r1');
t0 = performance.now();
raf = requestAnimationFrame(tick);
}
gridHost.addEventListener('click', (e) => {
if (phase !== 'r1') return;
const cell = e.target.closest('.rcell');
if (!cell) return;
if (cell.dataset.app !== target) {
shake(cell);
return;
}
t1 = performance.now() - t0;
t1El.textContent = fmt(t1);
cell.classList.add('hit');
setPhase('between');
roundEl.textContent = 'Round 2';
msgEl.textContent = 'The same app, in the list.';
verdict.textContent = 'Get ready.';
const mine = run;
let n = 3;
const count = () => {
if (phase !== 'between' || mine !== run) return;
if (n === 0) {
list.reset();
setPhase('r2');
verdict.textContent = `Round 2: find ${target} in the list.`;
t0 = performance.now();
raf = requestAnimationFrame(tick);
return;
}
roundEl.textContent = String(n);
n--;
setTimeout(count, 620);
};
setTimeout(count, 1100);
});
function tappedRow(name, row) {
if (phase !== 'r2') return;
if (name !== target) {
shake(row);
return;
}
const t2 = performance.now() - t0;
t2El.textContent = fmt(t2);
setPhase('done');
label('Run it again');
const gap = (Math.abs(t1 - t2) / 1000).toFixed(1);
if (gap === '0.0') verdict.textContent = 'Both the same, to a tenth of a second.';
else verdict.textContent = `The ${t2 < t1 ? 'list' : 'grid'} was ${gap} s quicker.`;
}
/** Escape stops a round: the cells and rows can't be reached from the keyboard. */
function stop() {
cancelAnimationFrame(raf);
run++;
setPhase('idle');
roundEl.textContent = 'Round 1';
msgEl.textContent = 'Press Start.';
t1El.textContent = '–';
t2El.textContent = '–';
verdict.textContent = 'Stopped.';
label('Start');
list.reset();
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && (phase === 'r1' || phase === 'between' || phase === 'r2')) stop();
});
startBtn.addEventListener('click', start);
buildGrid();
setPhase('idle');
return { render: () => list.render() };
}
/* ------------------------------------------------------------------ page */
/** "Coming in 0.16.0" until VERSION reaches it, then "New in 0.16.0". */
function cmpVersion(a, b) {
const x = a.split('.').map(Number);
const y = b.split('.').map(Number);
for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0) ? 1 : -1;
return 0;
}
function since() {
document.querySelectorAll('[data-since]').forEach((el) => {
const v = el.dataset.since;
el.textContent = `${cmpVersion(VERSION, v) >= 0 ? 'New' : 'Coming'} in ${v}`;
});
}
function boot() {
document.querySelectorAll('[data-version]').forEach((el) => { el.textContent = VERSION; });
since();
const phones = {};
for (const host of document.querySelectorAll('[data-phone]')) phones[host.dataset.phone] = new Phone(host);
// Live time and date in every phone.
const cycle = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions().hourCycle || 'h23';
const h24 = !/h1[12]/.test(cycle);
function tick() {
const d = new Date();
const hh = d.getHours();
const mm = String(d.getMinutes()).padStart(2, '0');
const now = h24 ? `${String(hh).padStart(2, '0')}:${mm}` : `${((hh + 11) % 12) + 1}:${mm}`;
const date = d.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
Object.values(phones).forEach((p) => p.tick(now, date));
document.querySelectorAll('.rgrid ~ .sbar .sbar__time').forEach((el) => { el.textContent = now; });
}
const story = phones.story ? setupStory(phones.story) : null;
const play = phones.play
? setupPlay(phones.play, { caption: document.querySelector('[data-caption]'), demos: document.querySelector('[data-demos]'), keyboard: true, armable: true })
: null;
const race = phones.race ? setupRace(phones.race) : null;
const hero = phones.hero ? setupHero(phones.hero, phones.quick) : null;
tick();
setInterval(tick, 10000);
const rerender = () => {
if (hero) hero();
if (story) story(true);
if (play) play.render();
if (race) race.render();
};
setupLook(phones, rerender, play ? play.say : () => {});
// The picture widget turns to its next photo every ten seconds, as the app's does.
if (!reduced) setInterval(() => { if (!reduced) Object.values(phones).forEach((p) => p.nextPicture()); }, PICTURE_MS);
// The phones' face is measured in the marks' labels: measure again once it is in.
const remeasure = () => {
Object.values(phones).forEach((p) => p.measure());
rerender();
};
if (document.fonts) {
if (document.fonts.ready) document.fonts.ready.then(remeasure);
if (document.fonts.addEventListener) document.fonts.addEventListener('loadingdone', remeasure);
}
let ticking = false;
window.addEventListener('scroll', () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
ticking = false;
if (story) story();
});
}, { passive: true });
window.addEventListener('resize', () => {
if (story) story(true);
if (hero) hero();
});
motion.addEventListener?.('change', (e) => {
reduced = e.matches;
if (story) story(true);
});
if (hero) hero();
if (story) story(true);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
else boot();
})();