cuetake 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Follows the Tabs a Take shows (ADR 0008): the first page, and every page a Tab, or an iframe in it,
3
+ * opens as a new tab or a popup window. Pages the Scenario opens itself with `context.newPage()` are
4
+ * not followed. `watch(tab)` is called as each Tab opens; `start(tab)` then begins recording it, one Tab
5
+ * at a time. A Tab another came in front of while it started goes back behind.
6
+ *
7
+ * Which Tab is in front follows the browser: a new Tab comes in front when it opens, and when it closes
8
+ * the Tab that opened it comes back (or, if that one closed too, its nearest open opener). Any other
9
+ * Tab comes back only through `switchTo`. Times are epoch milliseconds.
10
+ */
11
+ export function followTabs(first, { watch = () => {}, start = async () => {} } = {}) {
12
+ const tabs = [], fronts = [];
13
+ let front = null, starting = Promise.resolve();
14
+ const toFront = tab => {
15
+ if (front === tab) return;
16
+ front = tab;
17
+ fronts.push({ ms: Date.now(), tab: tab.id });
18
+ };
19
+ const add = (page, opener) => {
20
+ const tab = { id: tabs.length, page, opener: opener?.id ?? null, openedMs: Date.now(), closedMs: null, viewport: page.viewportSize(), url: page.url() };
21
+ tabs.push(tab);
22
+ watch(tab);
23
+ page.on('popup', popup => toFront(add(popup, tab)));
24
+ page.on('close', () => {
25
+ tab.closedMs = Date.now();
26
+ if (front !== tab) return;
27
+ let back = tabs[tab.opener];
28
+ while (back?.closedMs) back = tabs[back.opener];
29
+ back ??= tabs.findLast(other => !other.closedMs);
30
+ if (!back) return;
31
+ toFront(back);
32
+ back.page.bringToFront().catch(() => {});
33
+ });
34
+ // A Tab that closes before it could be recorded is left out; any other failure stops the Take.
35
+ tab.ready = starting = starting.catch(() => {}).then(() => start(tab)).then(async () => {
36
+ tab.recorded = true;
37
+ if (front !== tab) await front.page.bringToFront().catch(() => {});
38
+ }, error => {
39
+ if (!page.isClosed()) throw error;
40
+ tab.recorded = false;
41
+ });
42
+ tab.ready.catch(() => {});
43
+ return tab;
44
+ };
45
+ front = add(first, null);
46
+ const of = page => tabs.find(tab => tab.page === page);
47
+ return {
48
+ get front() { return front; },
49
+ fronts,
50
+ list: () => tabs,
51
+ of,
52
+ /** Resolves once the Tab showing `page` records. */
53
+ ready: page => of(page)?.ready ?? Promise.reject(new Error('This page is not a Tab of the Take')),
54
+ /** Resolves once every Tab opened so far records or has closed unrecorded; rejects if one failed to start. */
55
+ started: () => Promise.all(tabs.map(tab => tab.ready)),
56
+ async switchTo(page) {
57
+ const tab = of(page);
58
+ if (!tab) throw new Error('d.switchTo needs a Tab of the Take: the first page or one the demo opened. Capture does not follow pages opened with context.newPage()');
59
+ if (tab.closedMs) throw new Error(`Tab ${tab.id} has closed`);
60
+ await page.bringToFront();
61
+ toFront(tab);
62
+ },
63
+ };
64
+ }
package/src/frames.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Where an iframe's content starts in its parent's viewport, in CSS pixels, and how much it is scaled:
3
+ * inside its border and padding, after scrolling, positioning and transforms. It runs in the page, in
4
+ * the iframe's parent document, so it works for a cross-origin iframe too. A rotated or skewed iframe
5
+ * gets the scale of its bounding box, which is only near.
6
+ */
7
+ export function contentOf(element) {
8
+ const r = element.getBoundingClientRect(), style = getComputedStyle(element);
9
+ const sx = element.offsetWidth ? r.width / element.offsetWidth : 1, sy = element.offsetHeight ? r.height / element.offsetHeight : 1;
10
+ return { x: r.x + (element.clientLeft + parseFloat(style.paddingLeft)) * sx, y: r.y + (element.clientTop + parseFloat(style.paddingTop)) * sy, sx, sy };
11
+ }
12
+
13
+ /**
14
+ * A located element's border box in top-level CSS pixels, mapped up through every iframe it is in, or
15
+ * null when it shows no box. Playwright's own boundingBox places an element in a cross-origin iframe
16
+ * from the iframe's outer edge, unscaled, so it misses the iframe's border, padding and scale.
17
+ */
18
+ export async function boxOnPage(locator) {
19
+ const handle = await locator.elementHandle();
20
+ try {
21
+ const box = await handle.evaluate(e => e.getClientRects().length ? e.getBoundingClientRect().toJSON() : null);
22
+ return box && onPage(await placeOf(await handle.ownerFrame()), box);
23
+ } finally { await handle.dispose(); }
24
+ }
25
+
26
+ /**
27
+ * Where a frame's viewport shows in top-level CSS pixels: the offset of its origin and its scale,
28
+ * through every iframe it is in. The top frame's is { x: 0, y: 0, sx: 1, sy: 1 }.
29
+ */
30
+ export async function placeOf(frame) {
31
+ let map = { x: 0, y: 0, sx: 1, sy: 1 };
32
+ for (let f = frame; f?.parentFrame(); f = f.parentFrame()) {
33
+ const element = await f.frameElement();
34
+ const content = await element.evaluate(contentOf).finally(() => element.dispose());
35
+ map = { x: content.x + map.x * content.sx, y: content.y + map.y * content.sy, sx: map.sx * content.sx, sy: map.sy * content.sy };
36
+ }
37
+ return map;
38
+ }
39
+
40
+ /** A box in a frame's CSS pixels placed in top-level CSS pixels by the frame's `map` (placeOf). */
41
+ export const onPage = (map, box) => ({ x: map.x + box.x * map.sx, y: map.y + box.y * map.sy, width: box.width * map.sx, height: box.height * map.sy });
package/src/look.js CHANGED
@@ -5,23 +5,27 @@ import { merge } from './edit.js';
5
5
  import { absolute, bundle, codeRefs, fileRefs } from './styles.js';
6
6
 
7
7
  /**
8
- * A Look is the part of an Edit that does not depend on one Take: everything except camera targets,
9
- * the address bar's url, the frame rate, the Shortcuts and the Narration's Lines. A Look sets only what
10
- * it names, and is not validated.
8
+ * A Look is the part of an Edit that does not depend on one Take: everything except camera targets and scrolls,
9
+ * the address bar's url and its changes, where popups sit, the frame rate, the Shortcuts, the fast-forwards, the masks and the Narration's Lines. A
10
+ * Look sets only what it names, and is not validated.
11
11
  */
12
12
  export const mergeLook = merge;
13
13
 
14
14
  /** The Look an Edit carries. */
15
15
  export function lookFromEdit(edit) {
16
- const { schemaVersion, narration, shortcuts, output: { fps, ...output } = {}, frame, camera: { targets, ...camera } = {}, ...rest } = edit;
17
- const { url, ...styling } = frame ?? {};
18
- return { ...rest, output, frame: styling, camera };
16
+ const { schemaVersion, narration, shortcuts, fastForward, masks, output: { fps, ...output } = {}, frame, camera: { targets, scrolls, ...camera } = {}, tabs: { placement, ...tabs } = {}, ...rest } = edit;
17
+ const { url, urls, ...styling } = frame ?? {};
18
+ return { ...rest, output, frame: styling, camera, tabs };
19
19
  }
20
20
 
21
- /** The Edit with a Look adopted. Camera targets, the frame rate, the Shortcuts and the Lines stay; the address bar keeps its url, else shows `host`. */
21
+ /**
22
+ * The Edit with a Look adopted. Camera targets, the frame rate, the Shortcuts, the fast-forwards, the
23
+ * masks, the Lines and where popups sit stay; the address bar keeps its url and changes, else shows `host`.
24
+ */
22
25
  export function applyLook(edit, look, host) {
23
26
  const next = merge(edit, look);
24
- next.frame = { ...next.frame, url: edit.frame?.url ?? host };
27
+ next.frame = { ...next.frame, url: edit.frame?.url ?? host, ...(edit.frame?.urls && { urls: edit.frame.urls }) };
28
+ if (edit.tabs?.placement) next.tabs = { ...next.tabs, placement: edit.tabs.placement };
25
29
  return next;
26
30
  }
27
31
 
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Keys the App Director presses, as macOS posts them. Pure, no imports.
3
+ *
4
+ * A Scenario names keys as Playwright does ('Meta+K', 'Enter', 'Shift+ArrowUp', 'ControlOrMeta+Z').
5
+ * Each names the virtual key code to post, by its place on an ANSI keyboard, the modifiers to hold, and
6
+ * the keydown a page would see for it, so the Timeline records the same Shortcut a page would.
7
+ */
8
+
9
+ // [macOS virtual key code, DOM key, DOM code] for the keys that are not a letter or digit.
10
+ const NAMED = {
11
+ Enter: [36, 'Enter', 'Enter'], Tab: [48, 'Tab', 'Tab'], Space: [49, ' ', 'Space'], Backspace: [51, 'Backspace', 'Backspace'],
12
+ Escape: [53, 'Escape', 'Escape'], Delete: [117, 'Delete', 'Delete'], Home: [115, 'Home', 'Home'], End: [119, 'End', 'End'],
13
+ PageUp: [116, 'PageUp', 'PageUp'], PageDown: [121, 'PageDown', 'PageDown'],
14
+ ArrowLeft: [123, 'ArrowLeft', 'ArrowLeft'], ArrowRight: [124, 'ArrowRight', 'ArrowRight'], ArrowDown: [125, 'ArrowDown', 'ArrowDown'], ArrowUp: [126, 'ArrowUp', 'ArrowUp'],
15
+ F1: [122, 'F1', 'F1'], F2: [120, 'F2', 'F2'], F3: [99, 'F3', 'F3'], F4: [118, 'F4', 'F4'], F5: [96, 'F5', 'F5'], F6: [97, 'F6', 'F6'],
16
+ F7: [98, 'F7', 'F7'], F8: [100, 'F8', 'F8'], F9: [101, 'F9', 'F9'], F10: [109, 'F10', 'F10'], F11: [103, 'F11', 'F11'], F12: [111, 'F12', 'F12'],
17
+ '-': [27, '-', 'Minus'], '=': [24, '=', 'Equal'], '[': [33, '[', 'BracketLeft'], ']': [30, ']', 'BracketRight'], '\\': [42, '\\', 'Backslash'],
18
+ ';': [41, ';', 'Semicolon'], "'": [39, "'", 'Quote'], ',': [43, ',', 'Comma'], '.': [47, '.', 'Period'], '/': [44, '/', 'Slash'], '`': [50, '`', 'Backquote'],
19
+ };
20
+ const LETTERS = { A: 0, S: 1, D: 2, F: 3, H: 4, G: 5, Z: 6, X: 7, C: 8, V: 9, B: 11, Q: 12, W: 13, E: 14, R: 15, Y: 16, T: 17, O: 31, U: 32, I: 34, P: 35, L: 37, J: 38, K: 40, N: 45, M: 46 };
21
+ const DIGITS = { 1: 18, 2: 19, 3: 20, 4: 21, 6: 22, 5: 23, 9: 25, 7: 26, 8: 28, 0: 29 };
22
+ // Modifiers in macOS order, each with the keydown flag a page sees.
23
+ const MODIFIERS = [['Control', 'control', 'ctrlKey'], ['Alt', 'option', 'altKey'], ['Shift', 'shift', 'shiftKey'], ['Meta', 'command', 'metaKey']];
24
+
25
+ /** The key code and DOM key and code for one key name, or null. */
26
+ function keyOf(name) {
27
+ const letter = name.length === 1 ? name.toUpperCase() : /^Key[A-Z]$/.test(name) ? name.slice(3) : null;
28
+ if (letter in LETTERS) return [LETTERS[letter], letter.toLowerCase(), `Key${letter}`];
29
+ const digit = /^\d$/.test(name) ? name : /^Digit\d$/.test(name) ? name.slice(5) : null;
30
+ if (digit !== null) return [DIGITS[digit], digit, `Digit${digit}`];
31
+ return NAMED[name] ?? null;
32
+ }
33
+
34
+ /** `keys`, such as 'Meta+K', as `{ keyCode, modifiers, down }`: what to post, what to hold, and the keydown a page would see. */
35
+ export function macKeys(keys) {
36
+ // Every part before the last '+' is a modifier; the rest is the key.
37
+ const [, prefix, name] = String(keys).match(/^((?:[^+]+\+)*)(.*)$/);
38
+ const held = new Set(prefix.split('+').filter(Boolean).map(part => part === 'ControlOrMeta' ? 'Meta' : part));
39
+ for (const part of held) if (!MODIFIERS.some(([modifier]) => modifier === part)) throw new Error(`d.press does not know the modifier '${part}'; use Control, Alt, Shift, Meta or ControlOrMeta`);
40
+ const key = keyOf(name);
41
+ if (!key) throw new Error(`d.press does not know the key '${name}'; use names such as Enter, Escape, Tab, Space, ArrowUp, a letter or a digit, as in 'Meta+K'`);
42
+ const [keyCode, domKey, code] = key, on = MODIFIERS.filter(([modifier]) => held.has(modifier));
43
+ return {
44
+ keyCode, modifiers: on.map(([, mac]) => mac),
45
+ down: { key: domKey, code, ...Object.fromEntries(MODIFIERS.map(([modifier, , flag]) => [flag, held.has(modifier)])) },
46
+ };
47
+ }
package/src/masks.js ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Masks, shared by Node and the render page. Pure functions, no imports.
3
+ *
4
+ * A Mask hides or points at a region of a Tab's page for a span of the Take: `blur` blurs it past
5
+ * reading, `cover` fills it with a solid color, and `spotlight` dims everything outside it. A mask
6
+ * names either a fixed `box` in its Tab's CSS pixels, or an `element`: one of the Timeline's
7
+ * `elements`, whose boxes Capture recorded over time. Its `start` and `end` are Source seconds; without
8
+ * them it runs from the start or to the end of the Take. Masks sit on the page under the camera.
9
+ */
10
+
11
+ /**
12
+ * Each effect's parameters: `padding`, `radius` (corner), `blur` and `feather` (how far the light
13
+ * falls off across the region's edge) in CSS px; `color` as '#rrggbb'; `dim`, the share of light taken
14
+ * from the rest of the frame; `ease` in Final seconds.
15
+ */
16
+ export const MASK_EFFECTS = {
17
+ blur: { blur: 16, padding: 4, radius: 6 },
18
+ cover: { color: '#000000', padding: 4, radius: 6 },
19
+ spotlight: { dim: 0.6, padding: 8, radius: 10, feather: 16, ease: 0.3 },
20
+ };
21
+
22
+ /** The effects, as messages list them: "blur, cover or spotlight". */
23
+ export const EFFECT_NAMES = Object.keys(MASK_EFFECTS).join(', ').replace(/, (\w+)$/, ' or $1');
24
+
25
+ // Seconds before and after a moment whose boxes a blur or cover also hides. Tab capture shows a
26
+ // change tens of milliseconds after the page made it, more on a busy machine, so the Source can still
27
+ // show an element where it was after its box has moved. Capture sees an element the page replaced
28
+ // elsewhere, or one in a new document, only when the Director next watches it (director.js).
29
+ const SLACK = { before: 0.2, after: 0.25 };
30
+
31
+ /** Below this many CSS px, a blur leaves body text readable. */
32
+ const LEAST_BLUR = 8;
33
+
34
+ const isColor = value => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value);
35
+ const isBox = box => box && ['x', 'y', 'width', 'height'].every(key => typeof box[key] === 'number' && Number.isFinite(box[key])) && box.width > 0 && box.height > 0;
36
+
37
+ /** A mask as messages name it, such as "Mask 2 (blur from 1.20 s)". */
38
+ const nameOf = (mask, i) => `Mask ${i} (${mask.effect}${typeof mask.start === 'number' ? ` from ${mask.start.toFixed(2)} s` : ''})`;
39
+
40
+ /**
41
+ * What stops Render from masking as the Edit asks, each naming its mask: an unknown effect, a mask
42
+ * with neither or both of a box and an element the Timeline recorded (`elements`), a box on a Tab the
43
+ * Take does not show (`tabs`, their ids, when given), an empty span, a color that is not '#rrggbb', or
44
+ * a blur too weak to hide text. A mask Render cannot draw would show what it hides, so any of these stops it.
45
+ */
46
+ export function maskProblems(masks = [], elements = [], tabs = null) {
47
+ if (!Array.isArray(masks)) return ['masks must be a list of masks'];
48
+ const ids = new Set(elements.map(element => element.id));
49
+ return masks.flatMap((mask, i) => {
50
+ if (!(mask?.effect in MASK_EFFECTS)) return [`Mask ${i} has effect '${mask?.effect}'; use ${EFFECT_NAMES}`];
51
+ const name = nameOf(mask, i), problems = [];
52
+ if (mask.element !== undefined && mask.box !== undefined) problems.push(`${name} names both a box and an element; keep one`);
53
+ else if (mask.element !== undefined) { if (!ids.has(mask.element)) problems.push(`${name} follows element ${mask.element}, which the Timeline does not record`); }
54
+ else if (!isBox(mask.box)) problems.push(`${name} needs a box { x, y, width, height } in CSS pixels, or the element a Scenario masked`);
55
+ else if (tabs && !tabs.includes(mask.tab ?? 0)) problems.push(`${name} is on Tab ${mask.tab}, which the Take does not show; its Tabs are ${tabs.join(', ')}`);
56
+ if (mask.color !== undefined && !isColor(mask.color)) problems.push(`${name} has color '${mask.color}'; use '#rrggbb'`);
57
+ const { start = 0, end = Infinity } = mask;
58
+ if (!(typeof start === 'number' && typeof end === 'number' && end > start)) problems.push(`${name} needs a start before its end, in seconds`);
59
+ const blur = mask.blur ?? MASK_EFFECTS.blur.blur;
60
+ if (mask.effect === 'blur' && !(blur >= LEAST_BLUR)) problems.push(`${name} blurs ${blur} CSS px, too little to hide text; use at least ${LEAST_BLUR}`);
61
+ return problems;
62
+ });
63
+ }
64
+
65
+ const padded = ({ x, y, width, height }, p) => ({ x: x - p, y: y - p, width: width + 2 * p, height: height + 2 * p });
66
+ const rectOf = ([x, y, width, height]) => ({ x, y, width, height });
67
+
68
+ /** The index of the last sample at or before Source time `s`, or the first: a box holds until the next one, and back to the start. */
69
+ function heldAt(boxes, s) {
70
+ let low = 0, high = boxes.length - 1, found = 0;
71
+ while (low <= high) { const mid = (low + high) >> 1; if (boxes[mid][0] <= s) { found = mid; low = mid + 1; } else high = mid - 1; }
72
+ return found;
73
+ }
74
+
75
+ /**
76
+ * An element's boxes at Source time `s`, as rects: those it held then, or with `slack`, every box it
77
+ * held from `slack.before` seconds before to `slack.after` after. A sample `[t, ...boxes]` lists each
78
+ * element the locator matched, as [x, y, width, height]; one without boxes means none showed.
79
+ */
80
+ export function elementBoxesAt(boxes, s, slack = { before: 0, after: 0 }) {
81
+ if (!boxes?.length) return [];
82
+ const from = heldAt(boxes, s - slack.before), to = heldAt(boxes, s + slack.after), seen = new Set(), rects = [];
83
+ for (const sample of boxes.slice(from, to + 1)) for (const box of sample.slice(1)) {
84
+ const key = box.join();
85
+ if (!seen.has(key)) { seen.add(key); rects.push(rectOf(box)); }
86
+ }
87
+ return rects;
88
+ }
89
+
90
+ /**
91
+ * The masks through the Final: `at(t)` lists those showing at Final time `t`, each with its index in
92
+ * `masks`, its Tab, its effect and parameters, its `opacity` and its `rects`, padded, in its Tab's CSS
93
+ * pixels. `map` is the Take's time map (time-map.js).
94
+ */
95
+ export function maskTrack(masks = [], elements = [], map) {
96
+ const byId = new Map(elements.map(element => [element.id, element]));
97
+ const placed = masks.map((mask, index) => {
98
+ const { effect, box, element: id, start = 0, end = Infinity, tab = 0, ...rest } = mask;
99
+ const params = { ...MASK_EFFECTS[effect], ...rest }, element = byId.get(id), slack = effect === 'spotlight' ? undefined : SLACK;
100
+ const rects = element ? s => elementBoxesAt(element.boxes, s, slack) : () => [box];
101
+ return { index, tab: element ? element.tab : tab, effect, params, from: map.outputAt(start), until: end === Infinity ? map.duration : map.outputAt(end), rects };
102
+ });
103
+ return {
104
+ at(t) {
105
+ const s = map.sourceAt(t);
106
+ // A spotlight eases in after its start and out before its end, in Final time; a blur or cover is whole at once.
107
+ const opacity = ({ effect, params: { ease }, from, until }) => effect !== 'spotlight' || !(ease > 0) ? 1 : Math.max(0, Math.min(1, (t - from) / ease, (until - t) / ease));
108
+ return placed.filter(mask => t >= mask.from && t < mask.until).map(({ index, tab, effect, params, rects, ...mask }) => ({
109
+ index, tab, effect, opacity: opacity({ effect, params, ...mask }), rects: rects(s).map(r => padded(r, params.padding)), ...params,
110
+ })).filter(mask => mask.rects.length);
111
+ },
112
+ };
113
+ }
114
+
115
+ /**
116
+ * At most `n` of `items` (each `{ rect, ... }`), the rest merged: past `n`, they become one item, the
117
+ * first of them with a rect around them all, so a box that does not fit one pass is hidden more widely, never shown.
118
+ */
119
+ export function mergedPast(items, n) {
120
+ if (items.length <= n) return items;
121
+ const rest = items.slice(n - 1);
122
+ const left = Math.min(...rest.map(({ rect }) => rect.x)), top = Math.min(...rest.map(({ rect }) => rect.y));
123
+ const right = Math.max(...rest.map(({ rect }) => rect.x + rect.width)), bottom = Math.max(...rest.map(({ rect }) => rect.y + rect.height));
124
+ return [...items.slice(0, n - 1), { ...rest[0], rect: { x: left, y: top, width: right - left, height: bottom - top } }];
125
+ }
126
+
127
+ /**
128
+ * Warnings for masks that drew nothing: each that follows an element its locator never matched on the
129
+ * page during its span, which usually means a locator that misses or a span before the element shows.
130
+ */
131
+ export function maskWarnings(masks = [], elements = []) {
132
+ const byId = new Map(elements.map(element => [element.id, element]));
133
+ return masks.flatMap((mask, i) => {
134
+ const element = byId.get(mask.element);
135
+ if (!element) return [];
136
+ const { start = 0, end = Infinity } = mask, { boxes } = element;
137
+ const seen = boxes.length && (boxes[heldAt(boxes, start)].length > 1 || boxes.some(([t, ...shown]) => t > start && t < end && shown.length));
138
+ return seen ? [] : [`${nameOf(mask, i)} found no ${element.name} on the page during its span, so it drew nothing; check the locator, or when the element shows`];
139
+ });
140
+ }
package/src/motion.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * How the Director's hand moves: durations from Fitts's law, a quick start and a long settle, a
3
- * slight arc, pauses around presses and Shortcuts, a held click or key and uneven typing. Pure and
3
+ * slight arc, pauses around presses and Shortcuts, a held click or key, uneven typing and scrolls that
4
+ * flick quickly and settle long. Pure and
4
5
  * seeded, so a Scenario moves the same way on every recording. CSS pixels and milliseconds throughout.
5
6
  */
6
7
 
@@ -10,7 +11,9 @@ const DRAG_SLOWDOWN = 1.5; // a held button makes people slower
10
11
  const POINT_SIZE = 24; // target size for moves to a bare point
11
12
  const BEND = 0.1, MAX_BEND = 80; // the arc's sideways offset, as a share of the distance and in CSS px
12
13
  const LANDING = 0.15, MAX_LANDING = 8; // a click lands at most this share of its box's size, and CSS px, from the center
13
- const PAUSES = { beforePress: 120, press: 100, afterRelease: 150, afterGrab: 100, beforeDrop: 100, beforeKey: 150, afterKey: 250 }; // press: how long a click or key is held
14
+ const SCROLL_MS = 300, SCROLL_MS_PER_BIT = 300, SCROLL_UNIT = 300; // a scroll takes SCROLL_MS + SCROLL_MS_PER_BIT * log2(distance / SCROLL_UNIT + 1)
15
+ const MAX_SCROLL_SPEED = 3000; // CSS px/s on average: a quick flick of a wheel or trackpad
16
+ const PAUSES = { beforePress: 120, press: 100, afterRelease: 150, afterGrab: 100, beforeDrop: 100, beforeKey: 150, afterKey: 250, afterScroll: 200 }; // press: how long a click or key is held
14
17
  const PAUSE_JITTER = 0.25, TYPING_JITTER = 0.4, WORD_BREAK = 1.5;
15
18
 
16
19
  /** A deterministic source of numbers in [0, 1) (mulberry32). */
@@ -31,8 +34,14 @@ export function reachMs(distance, size = POINT_SIZE, { speed = 1, drag = false }
31
34
  return Math.max(fitts, distance / MAX_AVERAGE_SPEED * 1000) * (drag ? DRAG_SLOWDOWN : 1) / speed;
32
35
  }
33
36
 
34
- /** Progress along a move at time share `t`: minimum-jerk, warped so it peaks early and settles long. */
35
- const ease = t => { const u = t ** 0.75; return u * u * u * (10 - 15 * u + 6 * u * u); };
37
+ /** How long a person takes to scroll `distance` CSS px: longer the farther, but a long scroll flicks fast. */
38
+ export function scrollMs(distance, { speed = 1 } = {}) {
39
+ if (distance < 1) return 0;
40
+ return Math.max(SCROLL_MS + SCROLL_MS_PER_BIT * Math.log2(distance / SCROLL_UNIT + 1), distance / MAX_SCROLL_SPEED * 1000) / speed;
41
+ }
42
+
43
+ /** Progress along a move or scroll at time share `t`: minimum-jerk, warped so it peaks early and settles long. */
44
+ export const ease = t => { const u = t ** 0.75; return u * u * u * (10 - 15 * u + 6 * u * u); };
36
45
 
37
46
  /** A move from `from` to `to`: its duration and its point at time share `t`, along a slight arc. */
38
47
  export function reach(from, to, { size, duration, speed, drag, rand }) {