@hadoku/game-ui 0.1.271 → 0.1.272

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,186 @@
1
+ /**
2
+ * A game's frame rate, in its log. One `requestAnimationFrame` loop times the gap between frames while
3
+ * the game is on screen, its tab is visible and the page is drawing, and sends `perf` events (each one
4
+ * platform-wire's `ClientData`) to the host's `report`:
5
+ *
6
+ * - `what: 'stretch'` — a bad stretch: a second with {@link SLOW_IN_WINDOW} slow gaps, or one gap over
7
+ * {@link FREEZE_MS}, until the frames recover. One report per stretch, however long it lasts.
8
+ * - `what: 'board'` — what the game was doing at the stretch's worst frame (the host's `board`), with
9
+ * the page's own facts: the running animations by what they move and the DOM's size.
10
+ * - `what: 'loaf'` — one per long frame the browser attributed (Chrome's `long-animation-frame`): how its
11
+ * time split between script, the render phase's callbacks and style and layout, and the scripts that ran.
12
+ * - `what: 'work'` — where a reported stretch's time went, in any browser: the game's own hot paths by
13
+ * label (the host's `work`), and what was left, the browser's style, layout, paint and compositing.
14
+ * - `what: 'summary'` — every frame since the last summary, every {@link SUMMARY_EVERY_TURNS} turns, as
15
+ * the game ends and as the board or the tab closes: a baseline even when nothing went bad.
16
+ * - `what: 'phases'` — the same frames by the phase they were drawn in, beside each summary: one phase
17
+ * against another, whether or not anything went bad in either.
18
+ * - `what: 'env'` — once, beside the first summary: the machine and the browser a bad number might be,
19
+ * read apart from a regression, since two screens can draw the same board at very different rates —
20
+ * `devicePixelRatio`, the CPU's own core count, the GPU WebGL names back (empty where the browser
21
+ * hides or has none), the UI scale slider, and the display's own rate, read from the game's own calm
22
+ * frames rather than a fresh sample.
23
+ *
24
+ * A frame costs two clock reads, a few counter writes and one histogram bump: no allocation, no DOM read,
25
+ * no layout. Everything else is computed only when a stretch opens or a report goes out.
26
+ *
27
+ * It never asks for a frame the page would not draw. A `requestAnimationFrame` loop makes the browser
28
+ * draw every frame, and each frame the main thread draws samples every running animation, the ones the
29
+ * compositor runs included: a table of looping flyers costs the main thread a restyle of every part of
30
+ * every flyer sixty times a second, for as long as the game is open. So once nothing has been drawn for
31
+ * {@link QUIET_MS} (no DOM change but a quiet one, no input, no animation or transition starting:
32
+ * `pageActivity`), and no stretch is open, the loop stops. The next change starts it again. While it is
33
+ * stopped, a timer every {@link HEARTBEAT_MS} stands in for the frames: one that runs over
34
+ * {@link FREEZE_MS} late was a freeze, timed as a frame from when it was due. The frames a summary counts
35
+ * are the frames the page drew.
36
+ */
37
+ import type { ClientData } from '@wolffm/platform-wire/telemetry';
38
+ type Data = ClientData;
39
+ /**
40
+ * A gap over this is a slow frame, the kind a stretch is made of: a 60 Hz frame missed, motion at 30 fps.
41
+ * Motion running at ~38 fps is a drop a player sees, and a 33 ms gap never reaches {@link SLOW_MS}.
42
+ */
43
+ export declare const DROP_MS = 30;
44
+ /** The tier a stretch counts as `over50`: under 20 fps, two 60 Hz frames missed in a row. */
45
+ export declare const SLOW_MS = 50;
46
+ /** The second tier a stretch counts: under 10 fps, motion that visibly steps. */
47
+ export declare const VERY_SLOW_MS = 100;
48
+ /** One gap over this is a bad moment on its own: a fifth of a second with nothing drawn is seen by anyone. */
49
+ export declare const FREEZE_MS = 200;
50
+ /** Slow gaps inside one {@link WINDOW_MS} that make a bad moment: one or two are a decode or a GC pause, three in a second is motion that stutters. */
51
+ export declare const SLOW_IN_WINDOW = 3;
52
+ /** The window {@link SLOW_IN_WINDOW} is counted over. */
53
+ export declare const WINDOW_MS = 1000;
54
+ /** A stretch is over once this long passes with no slow gap: any shorter, and one long stall reads as several. */
55
+ export declare const RECOVER_MS = 1000;
56
+ /** A stretch that never recovers is reported at this length and goes on as a new one, so lag that never ends still reaches the log. */
57
+ export declare const MAX_STRETCH_MS = 15000;
58
+ /** At most one stretch report this often: a laggy game must not turn its own telemetry into more lag. */
59
+ export declare const REPORT_EVERY_MS = 10000;
60
+ /** At most this many stretch reports in one watch; the rest are counted in the summaries. */
61
+ export declare const MAX_REPORTS = 30;
62
+ /**
63
+ * The page's own facts (`pageFacts`: every running animation, the DOM's size) are read at most this
64
+ * often inside a stretch: one read can cost tens of ms on a busy board, and a stretch that keeps getting
65
+ * worse would read them at every new worst frame — the monitor adding the lag it reports.
66
+ */
67
+ export declare const PAGE_EVERY_MS = 1000;
68
+ /** How many of a stretch's longest frames are attributed, each in its own `loaf` event (the server takes 20 events a second). */
69
+ export declare const TOP_LONG_FRAMES = 3;
70
+ /** How many of a long frame's scripts are named. */
71
+ export declare const TOP_SCRIPTS = 3;
72
+ /** With nothing drawn for this long, the loop stops asking for frames (`pageActivity` starts it again). */
73
+ export declare const QUIET_MS = 1000;
74
+ /** While the loop is stopped, a timer this often times the main thread: a late one was a freeze. */
75
+ export declare const HEARTBEAT_MS = 100;
76
+ /** A summary every this many turns, beside the one as the game closes. */
77
+ export declare const SUMMARY_EVERY_TURNS = 4;
78
+ /** Gap histogram: 1 ms buckets below 128 ms, 16 ms buckets above, the last one open-ended. */
79
+ export declare const BUCKETS = 256;
80
+ /** Chrome's `PerformanceScriptTiming`, the fields read here (TypeScript's DOM lib has none of it yet). */
81
+ interface ScriptTiming {
82
+ readonly invoker: string;
83
+ readonly sourceFunctionName: string;
84
+ readonly sourceURL: string;
85
+ readonly sourceCharPosition: number;
86
+ readonly duration: number;
87
+ readonly forcedStyleAndLayoutDuration: number;
88
+ }
89
+ /** Chrome's `PerformanceLongAnimationFrameTiming`, or a `longtask` entry (which carries only the first two). */
90
+ export interface LongFrame {
91
+ readonly startTime: number;
92
+ readonly duration: number;
93
+ readonly renderStart?: number;
94
+ readonly styleAndLayoutStart?: number;
95
+ readonly blockingDuration?: number;
96
+ readonly scripts?: readonly ScriptTiming[];
97
+ }
98
+ /** The part of `PerformanceObserver` used here, so a test can stand one in. */
99
+ export interface ObserverClass {
100
+ readonly supportedEntryTypes?: readonly string[];
101
+ new (callback: (list: {
102
+ getEntries(): readonly unknown[];
103
+ }) => void): {
104
+ observe(options: {
105
+ type: string;
106
+ buffered?: boolean;
107
+ }): void;
108
+ disconnect(): void;
109
+ takeRecords?(): readonly unknown[];
110
+ };
111
+ }
112
+ export interface FrameWatchHost {
113
+ /** Where a `perf` event's data goes. */
114
+ report: (data: Data) => void;
115
+ /** What the game is doing, read as a stretch opens and again at each new worst frame in it. */
116
+ board: () => Data;
117
+ /** The page's own facts (DOM size, running animations), read with {@link FrameWatchHost.board}. Defaults to {@link pageFacts}. */
118
+ page?: () => Data;
119
+ /** The machine and the browser (`dpr`, `cores`, `gpu`, `scale`), read once a watch. Defaults to {@link envFacts}. */
120
+ env?: () => Data;
121
+ /** Test seams: the real `requestAnimationFrame`, `cancelAnimationFrame`, `performance.now`, `document` and `PerformanceObserver` by default. */
122
+ raf?: (callback: (t: number) => void) => number;
123
+ caf?: (handle: number) => void;
124
+ now?: () => number;
125
+ doc?: Pick<Document, 'visibilityState' | 'addEventListener' | 'removeEventListener'>;
126
+ /** Where a closing tab says so (`pagehide`): the real `window` by default. */
127
+ win?: Pick<Window, 'addEventListener' | 'removeEventListener' | 'innerWidth' | 'innerHeight'>;
128
+ observer?: ObserverClass | null;
129
+ /** What the game's own hot paths have spent so far, by label. Absent: a stretch's `work` names none, all of it the browser's. */
130
+ work?: () => ReadonlyMap<string, number>;
131
+ /** A DOM change inside such a node is not the page drawing anything new (a clock rewriting its text every second). */
132
+ quiet?: (node: Node) => boolean;
133
+ /** Calls `wake` whenever the page draws something new; returns the uninstall. {@link pageActivity} with {@link FrameWatchHost.quiet} by default. */
134
+ wakeOn?: (wake: () => void) => () => void;
135
+ /** The heartbeat's timer: `setTimeout`/`clearTimeout` by default. */
136
+ timer?: {
137
+ set: (callback: () => void, ms: number) => number;
138
+ clear: (handle: number) => void;
139
+ };
140
+ }
141
+ export interface FrameWatch {
142
+ /** The turn moved on: every {@link SUMMARY_EVERY_TURNS} turns, a summary. */
143
+ noteTurn(turn: number): void;
144
+ /** The phase the board is drawn in now: the frames after this count toward it in the `phases` report. */
145
+ notePhase(phase: string): void;
146
+ /** The game is over: a summary of it. */
147
+ noteGameOver(): void;
148
+ /** Stop: a stretch still open is reported, then a summary. */
149
+ dispose(): void;
150
+ }
151
+ /** The bucket a gap falls in. */
152
+ export declare function bucketOf(gap: number): number;
153
+ /** The gap at or under which `share` of the counted frames fell. */
154
+ export declare function percentile(histogram: Uint32Array, total: number, share: number): number;
155
+ /** One script of a long frame, in one field: `invoker|function|file:char|ms|f<forced style and layout ms>`. */
156
+ export declare function scriptField(s: ScriptTiming): string;
157
+ /** A long frame, as one `loaf` event's fields: when in the stretch, how long, and where its time went. */
158
+ export declare function loafFields(entry: LongFrame, stretchStart: number): Data;
159
+ /** The running animations, by what they move: a CSS animation's name, a transition's property, a script's element class. Top four. */
160
+ export declare function animationTop(animations: readonly Animation[]): string;
161
+ /** The page's own facts, read with the board's: the DOM's size and the animations running. */
162
+ export declare function pageFacts(): Data;
163
+ export declare function gpuRenderer(): string;
164
+ /**
165
+ * What the page's own hardware and settings are, read once (`env`, beside the first summary): what
166
+ * makes one screen differ from another, not a regression — `devicePixelRatio`, the CPU's
167
+ * core count Firefox and Chrome both offer, the GPU WebGL names back, and the UI scale slider
168
+ * (`--ui-scale`, a plain number — never a `calc()`, so `parseFloat` reads it straight).
169
+ */
170
+ export declare function envFacts(): Data;
171
+ /** Calls `wake` on everything that makes the page draw a frame (`ACTIVITY_EVENTS`, any DOM change outside a `quiet` node). Returns the uninstall. */
172
+ export declare function pageActivity(wake: () => void, quiet?: (node: Node) => boolean): () => void;
173
+ /** The attribution the browser offers: Chrome 123+'s long animation frames, else long tasks, else none (Firefox, Safari). */
174
+ export declare function attributionOf(observer: ObserverClass | null | undefined): 'loaf' | 'longtask' | 'none';
175
+ /** One phase's frames since the last summary. */
176
+ interface PhaseFrames {
177
+ frames: number;
178
+ ms: number;
179
+ drops: number;
180
+ slow: number;
181
+ worst: number;
182
+ }
183
+ /** A phase's frames in one field: `f<frames> <fps>fps d<over DROP_MS> s<over SLOW_MS> w<worst ms>`. */
184
+ export declare function phaseField(p: PhaseFrames): string;
185
+ export declare function watchFrames(host: FrameWatchHost): FrameWatch;
186
+ export {};
@@ -0,0 +1,592 @@
1
+ /**
2
+ * A gap over this is a slow frame, the kind a stretch is made of: a 60 Hz frame missed, motion at 30 fps.
3
+ * Motion running at ~38 fps is a drop a player sees, and a 33 ms gap never reaches {@link SLOW_MS}.
4
+ */
5
+ export const DROP_MS = 30;
6
+ /** The tier a stretch counts as `over50`: under 20 fps, two 60 Hz frames missed in a row. */
7
+ export const SLOW_MS = 50;
8
+ /** The second tier a stretch counts: under 10 fps, motion that visibly steps. */
9
+ export const VERY_SLOW_MS = 100;
10
+ /** One gap over this is a bad moment on its own: a fifth of a second with nothing drawn is seen by anyone. */
11
+ export const FREEZE_MS = 200;
12
+ /** Slow gaps inside one {@link WINDOW_MS} that make a bad moment: one or two are a decode or a GC pause, three in a second is motion that stutters. */
13
+ export const SLOW_IN_WINDOW = 3;
14
+ /** The window {@link SLOW_IN_WINDOW} is counted over. */
15
+ export const WINDOW_MS = 1_000;
16
+ /** A stretch is over once this long passes with no slow gap: any shorter, and one long stall reads as several. */
17
+ export const RECOVER_MS = 1_000;
18
+ /** A stretch that never recovers is reported at this length and goes on as a new one, so lag that never ends still reaches the log. */
19
+ export const MAX_STRETCH_MS = 15_000;
20
+ /** At most one stretch report this often: a laggy game must not turn its own telemetry into more lag. */
21
+ export const REPORT_EVERY_MS = 10_000;
22
+ /** At most this many stretch reports in one watch; the rest are counted in the summaries. */
23
+ export const MAX_REPORTS = 30;
24
+ /**
25
+ * The page's own facts (`pageFacts`: every running animation, the DOM's size) are read at most this
26
+ * often inside a stretch: one read can cost tens of ms on a busy board, and a stretch that keeps getting
27
+ * worse would read them at every new worst frame — the monitor adding the lag it reports.
28
+ */
29
+ export const PAGE_EVERY_MS = 1_000;
30
+ /** How many of a stretch's longest frames are attributed, each in its own `loaf` event (the server takes 20 events a second). */
31
+ export const TOP_LONG_FRAMES = 3;
32
+ /** How many of a long frame's scripts are named. */
33
+ export const TOP_SCRIPTS = 3;
34
+ /** With nothing drawn for this long, the loop stops asking for frames (`pageActivity` starts it again). */
35
+ export const QUIET_MS = 1_000;
36
+ /** While the loop is stopped, a timer this often times the main thread: a late one was a freeze. */
37
+ export const HEARTBEAT_MS = 100;
38
+ /** A summary every this many turns, beside the one as the game closes. */
39
+ export const SUMMARY_EVERY_TURNS = 4;
40
+ /** The last gaps, for what came before a stretch was recognised: a second at up to 512 fps. */
41
+ const RING = 512;
42
+ /** Long frames (or long tasks) kept for attribution: more than a {@link MAX_STRETCH_MS} stretch of them is old news. */
43
+ const LONG_KEEP = 48;
44
+ /** Gap histogram: 1 ms buckets below 128 ms, 16 ms buckets above, the last one open-ended. */
45
+ export const BUCKETS = 256;
46
+ /** The telemetry's text limit (`ScalarSchema`). */
47
+ const TEXT_MAX = 80;
48
+ /** The bucket a gap falls in. */
49
+ export function bucketOf(gap) {
50
+ return gap < 128 ? Math.floor(gap) : Math.min(BUCKETS - 1, 128 + Math.floor((gap - 128) / 16));
51
+ }
52
+ /** A bucket's upper edge, in ms: what a percentile reports. */
53
+ function bucketTop(i) {
54
+ return i < 128 ? i + 1 : 128 + (i - 127) * 16;
55
+ }
56
+ /** The gap at or under which `share` of the counted frames fell. */
57
+ export function percentile(histogram, total, share) {
58
+ const want = Math.max(1, Math.ceil(total * share));
59
+ let seen = 0;
60
+ for (let i = 0; i < BUCKETS; i += 1) {
61
+ seen += histogram[i];
62
+ if (seen >= want)
63
+ return bucketTop(i);
64
+ }
65
+ return bucketTop(BUCKETS - 1);
66
+ }
67
+ /** A URL's file name, without its query. */
68
+ function fileOf(url) {
69
+ if (url === '')
70
+ return '';
71
+ return url.split('?')[0].split('#')[0].split('/').pop() ?? '';
72
+ }
73
+ /** One script of a long frame, in one field: `invoker|function|file:char|ms|f<forced style and layout ms>`. */
74
+ export function scriptField(s) {
75
+ const invoker = /^https?:/.test(s.invoker) ? fileOf(s.invoker) : s.invoker;
76
+ const where = s.sourceURL === '' ? '' : `${fileOf(s.sourceURL).slice(0, 28)}:${s.sourceCharPosition}`;
77
+ return `${invoker.slice(0, 32)}|${s.sourceFunctionName.slice(0, 24)}|${where}|${Math.round(s.duration)}|f${Math.round(s.forcedStyleAndLayoutDuration)}`.slice(0, TEXT_MAX);
78
+ }
79
+ /** A long frame, as one `loaf` event's fields: when in the stretch, how long, and where its time went. */
80
+ export function loafFields(entry, stretchStart) {
81
+ const end = entry.startTime + entry.duration;
82
+ const render = entry.renderStart !== undefined && entry.renderStart > 0 ? entry.renderStart : end;
83
+ const layout = entry.styleAndLayoutStart !== undefined && entry.styleAndLayoutStart > 0 ? entry.styleAndLayoutStart : end;
84
+ const scripts = [...(entry.scripts ?? [])].sort((a, b) => b.duration - a.duration);
85
+ const fields = {
86
+ atMs: Math.round(entry.startTime - stretchStart),
87
+ ms: Math.round(entry.duration),
88
+ blockMs: Math.round(entry.blockingDuration ?? 0),
89
+ // Before the render phase: tasks, input, timers — the frame's script.
90
+ workMs: Math.round(render - entry.startTime),
91
+ // The render phase's own callbacks (rAF, ResizeObserver) before style and layout.
92
+ renderMs: Math.round(layout - render),
93
+ // Style, layout and paint.
94
+ layoutMs: Math.round(end - layout),
95
+ scripts: scripts.length,
96
+ forcedMs: Math.round(scripts.reduce((sum, s) => sum + s.forcedStyleAndLayoutDuration, 0)),
97
+ };
98
+ scripts.slice(0, TOP_SCRIPTS).forEach((s, i) => {
99
+ fields[`s${i + 1}`] = scriptField(s);
100
+ });
101
+ return fields;
102
+ }
103
+ /** The running animations, by what they move: a CSS animation's name, a transition's property, a script's element class. Top four. */
104
+ export function animationTop(animations) {
105
+ const counts = new Map();
106
+ for (const a of animations) {
107
+ if (a.playState !== 'running')
108
+ continue;
109
+ const named = a;
110
+ const target = a.effect?.target ?? null;
111
+ const label = named.animationName ?? (named.transitionProperty !== undefined ? `t:${named.transitionProperty}` : (target?.classList[0] ?? 'js'));
112
+ counts.set(label, (counts.get(label) ?? 0) + 1);
113
+ }
114
+ return [...counts]
115
+ .sort((a, b) => b[1] - a[1])
116
+ .slice(0, 4)
117
+ .map(([label, n]) => `${label}×${n}`)
118
+ .join(',')
119
+ .slice(0, TEXT_MAX);
120
+ }
121
+ /** The page's own facts, read with the board's: the DOM's size and the animations running. */
122
+ export function pageFacts() {
123
+ const animations = typeof document.getAnimations === 'function' ? document.getAnimations() : [];
124
+ return {
125
+ anims: animations.filter((a) => a.playState === 'running').length,
126
+ animTop: animationTop(animations),
127
+ dom: document.getElementsByTagName('*').length,
128
+ };
129
+ }
130
+ /**
131
+ * The GPU WebGL names back, read once and cached: `""` where the browser hides it (a privacy budget,
132
+ * no WebGL) or there is none (software rendering, `SwiftShader`/`llvmpipe`/`ANGLE (...)`'s own string
133
+ * still says so). A canvas never attached to the page, so the probe draws nothing. Never free, which is
134
+ * why it runs once a page and its answer is kept, not re-asked.
135
+ */
136
+ let gpuRendererCache = null;
137
+ export function gpuRenderer() {
138
+ if (gpuRendererCache !== null)
139
+ return gpuRendererCache;
140
+ gpuRendererCache = '';
141
+ try {
142
+ const gl = document.createElement('canvas').getContext('webgl');
143
+ if (gl !== null && gl !== undefined) {
144
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
145
+ const raw = info === null ? gl.getParameter(gl.RENDERER) : gl.getParameter(info.UNMASKED_RENDERER_WEBGL);
146
+ gpuRendererCache = String(raw).slice(0, TEXT_MAX);
147
+ }
148
+ }
149
+ catch {
150
+ // No WebGL, or the browser refuses the probe: "" stands for "can't tell," never a guess.
151
+ }
152
+ return gpuRendererCache;
153
+ }
154
+ /**
155
+ * What the page's own hardware and settings are, read once (`env`, beside the first summary): what
156
+ * makes one screen differ from another, not a regression — `devicePixelRatio`, the CPU's
157
+ * core count Firefox and Chrome both offer, the GPU WebGL names back, and the UI scale slider
158
+ * (`--ui-scale`, a plain number — never a `calc()`, so `parseFloat` reads it straight).
159
+ */
160
+ export function envFacts() {
161
+ const scale = typeof document === 'undefined' ? NaN : parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--ui-scale'));
162
+ return {
163
+ dpr: typeof window === 'undefined' || !Number.isFinite(window.devicePixelRatio) ? 1 : window.devicePixelRatio,
164
+ cores: typeof navigator === 'undefined' ? 0 : (navigator.hardwareConcurrency ?? 0),
165
+ gpu: gpuRenderer(),
166
+ scale: Number.isFinite(scale) ? scale : 1,
167
+ };
168
+ }
169
+ /** What makes the page draw: input, DOM changes, and animations and transitions starting. */
170
+ const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'pointerup', 'wheel', 'keydown', 'scroll', 'resize', 'animationstart', 'transitionrun'];
171
+ /** Calls `wake` on everything that makes the page draw a frame (`ACTIVITY_EVENTS`, any DOM change outside a `quiet` node). Returns the uninstall. */
172
+ export function pageActivity(wake, quiet = () => false) {
173
+ const observer = typeof MutationObserver === 'function' ? new MutationObserver((records) => records.some((r) => !quiet(r.target)) && wake()) : null;
174
+ observer?.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
175
+ const options = { capture: true, passive: true };
176
+ for (const type of ACTIVITY_EVENTS)
177
+ window.addEventListener(type, wake, options);
178
+ return () => {
179
+ observer?.disconnect();
180
+ for (const type of ACTIVITY_EVENTS)
181
+ window.removeEventListener(type, wake, options);
182
+ };
183
+ }
184
+ /** The attribution the browser offers: Chrome 123+'s long animation frames, else long tasks, else none (Firefox, Safari). */
185
+ export function attributionOf(observer) {
186
+ const types = observer?.supportedEntryTypes ?? [];
187
+ if (types.includes('long-animation-frame'))
188
+ return 'loaf';
189
+ if (types.includes('longtask'))
190
+ return 'longtask';
191
+ return 'none';
192
+ }
193
+ const NO_WORK = () => new Map();
194
+ const IDLE = { noteTurn: () => undefined, notePhase: () => undefined, noteGameOver: () => undefined, dispose: () => undefined };
195
+ /** A phase's frames in one field: `f<frames> <fps>fps d<over DROP_MS> s<over SLOW_MS> w<worst ms>`. */
196
+ export function phaseField(p) {
197
+ return `f${p.frames} ${Math.round((p.frames * 1000) / Math.max(1, p.ms))}fps d${p.drops} s${p.slow} w${Math.round(p.worst)}`;
198
+ }
199
+ /** The phases a `phases` event can carry beside its `what` (the telemetry's 16 fields). */
200
+ const PHASE_FIELDS = 15;
201
+ export function watchFrames(host) {
202
+ // A document that draws no frames (a test's, a server render) has none to time.
203
+ if (host.raf === undefined && typeof requestAnimationFrame !== 'function')
204
+ return IDLE;
205
+ const raf = host.raf ?? ((cb) => requestAnimationFrame(cb));
206
+ const caf = host.caf ?? ((h) => cancelAnimationFrame(h));
207
+ const now = host.now ?? (() => performance.now());
208
+ const doc = host.doc ?? document;
209
+ const win = host.win ?? window;
210
+ const page = host.page ?? pageFacts;
211
+ const env = host.env ?? envFacts;
212
+ const Observer = host.observer === undefined ? (typeof PerformanceObserver === 'function' ? PerformanceObserver : null) : host.observer;
213
+ const attribution = attributionOf(Observer);
214
+ const work = host.work ?? NO_WORK;
215
+ const wakeOn = host.wakeOn ?? ((wake) => pageActivity(wake, host.quiet));
216
+ const timer = host.timer ?? { set: (cb, ms) => window.setTimeout(cb, ms), clear: (h) => window.clearTimeout(h) };
217
+ /** What the game's hot paths had spent as the open stretch began. */
218
+ let workAtOpen = new Map();
219
+ let phase = 'none';
220
+ let phaseNow = null;
221
+ const phases = new Map();
222
+ // The last gaps and when each ended, oldest overwritten.
223
+ const gaps = new Float64Array(RING);
224
+ const ends = new Float64Array(RING);
225
+ let at = 0;
226
+ // When each of the last SLOW_IN_WINDOW slow gaps ended, and how long it was.
227
+ const slowEnds = new Float64Array(SLOW_IN_WINDOW);
228
+ const slowGaps = new Float64Array(SLOW_IN_WINDOW);
229
+ let slowAt = 0;
230
+ // Since the last summary.
231
+ const histogram = new Uint32Array(BUCKETS);
232
+ let frames = 0;
233
+ let watchedMs = 0;
234
+ let worst = 0;
235
+ let selfMs = 0;
236
+ let selfFrames = 0;
237
+ let stretches = 0;
238
+ let suppressedTotal = 0;
239
+ let summaryTurn = -1;
240
+ let lastTurn = -1;
241
+ // `env` fires once, beside whichever summary is first (`turns`, `over` or `end`).
242
+ let envSent = false;
243
+ // The open stretch: everything up to its last slow gap, and the frames since it (dropped if it recovers).
244
+ let open = false;
245
+ let start = 0;
246
+ let lastSlow = 0;
247
+ let sFrames = 0;
248
+ let sWorst = 0;
249
+ let sOver50 = 0;
250
+ let sOver100 = 0;
251
+ let sFreeze = false;
252
+ let tailFrames = 0;
253
+ // What the board was doing at the stretch's worst frame so far, and the page's facts as last read.
254
+ let board = {};
255
+ let pageRead = {};
256
+ let pageReadAt = -Infinity;
257
+ // Reports.
258
+ let n = 0;
259
+ let reports = 0;
260
+ let lastReportAt = -Infinity;
261
+ let suppressed = 0;
262
+ let last = -1;
263
+ let handle = null;
264
+ let disposed = false;
265
+ // When the page last drew something new; while the loop is stopped, the heartbeat and when it is due.
266
+ let lastWake = now();
267
+ let asleep = false;
268
+ let beat = null;
269
+ let beatDue = 0;
270
+ const long = [];
271
+ let observer = null;
272
+ const keep = (entries) => {
273
+ for (const e of entries) {
274
+ long.push(e);
275
+ if (long.length > LONG_KEEP)
276
+ long.shift();
277
+ }
278
+ };
279
+ if (Observer != null && attribution !== 'none') {
280
+ observer = new Observer((list) => keep(list.getEntries()));
281
+ observer.observe({ type: attribution === 'loaf' ? 'long-animation-frame' : 'longtask' });
282
+ }
283
+ function openStretch(t, gap) {
284
+ open = true;
285
+ // From the start of the oldest slow gap in the window — or this gap alone, for a freeze.
286
+ const oldest = slowAt >= SLOW_IN_WINDOW ? slowAt % SLOW_IN_WINDOW : -1;
287
+ const windowStart = oldest >= 0 && t - slowEnds[oldest] <= WINDOW_MS ? slowEnds[oldest] - slowGaps[oldest] : t - gap;
288
+ start = Math.min(windowStart, t - gap);
289
+ sFreeze = false;
290
+ sFrames = 0;
291
+ sWorst = 0;
292
+ sOver50 = 0;
293
+ sOver100 = 0;
294
+ tailFrames = 0;
295
+ // The frames already inside the stretch, this one included, newest first.
296
+ for (let k = 0; k < RING; k += 1) {
297
+ const i = (at - 1 - k + RING) % RING;
298
+ if (ends[i] <= start || ends[i] === 0)
299
+ break;
300
+ count(gaps[i]);
301
+ }
302
+ lastSlow = t;
303
+ workAtOpen = new Map(work());
304
+ snapshot(t);
305
+ }
306
+ /** The board as it is now, `t` into the stretch, only at a new worst; the page's facts at most every {@link PAGE_EVERY_MS}. */
307
+ function snapshot(t) {
308
+ if (t - pageReadAt >= PAGE_EVERY_MS) {
309
+ pageRead = page();
310
+ pageReadAt = t;
311
+ }
312
+ board = { atMs: Math.round(t - start), ...host.board(), ...pageRead };
313
+ }
314
+ function count(gap) {
315
+ sFrames += 1;
316
+ if (gap > sWorst)
317
+ sWorst = gap;
318
+ if (gap > SLOW_MS)
319
+ sOver50 += 1;
320
+ if (gap > VERY_SLOW_MS)
321
+ sOver100 += 1;
322
+ if (gap > FREEZE_MS)
323
+ sFreeze = true;
324
+ }
325
+ function closeStretch(why) {
326
+ open = false;
327
+ stretches += 1;
328
+ n += 1;
329
+ const end = lastSlow;
330
+ if (reports >= MAX_REPORTS || end - lastReportAt < REPORT_EVERY_MS) {
331
+ suppressed += 1;
332
+ suppressedTotal += 1;
333
+ return;
334
+ }
335
+ reports += 1;
336
+ lastReportAt = end;
337
+ const ms = Math.max(1, end - start);
338
+ if (observer?.takeRecords !== undefined)
339
+ keep(observer.takeRecords());
340
+ const inside = long.filter((e) => e.startTime < end && e.startTime + e.duration > start);
341
+ host.report({
342
+ what: 'stretch',
343
+ n,
344
+ ms: Math.round(ms),
345
+ frames: sFrames,
346
+ worstMs: Math.round(sWorst),
347
+ over50: sOver50,
348
+ over100: sOver100,
349
+ fps: Math.round((sFrames * 10_000) / ms) / 10,
350
+ freeze: sFreeze,
351
+ suppressed,
352
+ attribution,
353
+ longs: inside.length,
354
+ longMaxMs: Math.round(inside.reduce((m, e) => Math.max(m, e.duration), 0)),
355
+ why,
356
+ window: `${win.innerWidth}x${win.innerHeight}`,
357
+ });
358
+ suppressed = 0;
359
+ host.report({ what: 'board', n, ...board });
360
+ // The game's own work inside the stretch, by label; the rest of its frames' time was the browser's.
361
+ const spentIn = {};
362
+ let ours = 0;
363
+ for (const [label, total] of work()) {
364
+ const inStretch = total - (workAtOpen.get(label) ?? 0);
365
+ if (inStretch <= 0)
366
+ continue;
367
+ spentIn[label] = Math.round(inStretch);
368
+ ours += inStretch;
369
+ }
370
+ host.report({ what: 'work', n, ms: Math.round(ms), ours: Math.round(ours), oursPct: Math.round((ours * 100) / ms), ...spentIn });
371
+ if (attribution !== 'loaf')
372
+ return;
373
+ [...inside]
374
+ .sort((a, b) => b.duration - a.duration)
375
+ .slice(0, TOP_LONG_FRAMES)
376
+ .forEach((e, i) => host.report({ what: 'loaf', n, rank: i + 1, ...loafFields(e, start) }));
377
+ }
378
+ function tick(t) {
379
+ const began = now();
380
+ handle = null;
381
+ // The first frame after a start has no gap of its own; one after a wake is timed from it.
382
+ if (last >= 0)
383
+ time(t, began);
384
+ last = t;
385
+ if (!open && t - lastWake >= QUIET_MS)
386
+ sleep();
387
+ else
388
+ handle = raf(tick);
389
+ }
390
+ function time(t, began) {
391
+ const gap = t - last;
392
+ gaps[at] = gap;
393
+ ends[at] = t;
394
+ at = (at + 1) % RING;
395
+ frames += 1;
396
+ watchedMs += gap;
397
+ if (gap > worst)
398
+ worst = gap;
399
+ histogram[bucketOf(gap)] += 1;
400
+ if (phaseNow === null) {
401
+ phaseNow = { frames: 0, ms: 0, drops: 0, slow: 0, worst: 0 };
402
+ phases.set(phase, phaseNow);
403
+ }
404
+ phaseNow.frames += 1;
405
+ phaseNow.ms += gap;
406
+ if (gap > DROP_MS)
407
+ phaseNow.drops += 1;
408
+ if (gap > SLOW_MS)
409
+ phaseNow.slow += 1;
410
+ if (gap > phaseNow.worst)
411
+ phaseNow.worst = gap;
412
+ // The monitor's own cost is timed on frames outside a stretch: a stretch's reads and reports are its cost, not a frame's.
413
+ const plain = !open;
414
+ if (gap > DROP_MS) {
415
+ slowEnds[slowAt % SLOW_IN_WINDOW] = t;
416
+ slowGaps[slowAt % SLOW_IN_WINDOW] = gap;
417
+ slowAt += 1;
418
+ if (open) {
419
+ sFrames += tailFrames;
420
+ tailFrames = 0;
421
+ if (gap > sWorst)
422
+ snapshot(t);
423
+ count(gap);
424
+ lastSlow = t;
425
+ }
426
+ else if (gap > FREEZE_MS || (slowAt >= SLOW_IN_WINDOW && t - slowEnds[slowAt % SLOW_IN_WINDOW] <= WINDOW_MS)) {
427
+ openStretch(t, gap);
428
+ }
429
+ if (open && t - start >= MAX_STRETCH_MS)
430
+ closeStretch('max');
431
+ }
432
+ else if (open) {
433
+ tailFrames += 1;
434
+ if (t - lastSlow >= RECOVER_MS)
435
+ closeStretch('recovered');
436
+ }
437
+ if (plain && !open) {
438
+ selfMs += now() - began;
439
+ selfFrames += 1;
440
+ }
441
+ }
442
+ function startLoop() {
443
+ if (disposed || handle !== null || doc.visibilityState === 'hidden')
444
+ return;
445
+ stopBeat();
446
+ lastWake = now();
447
+ last = -1;
448
+ handle = raf(tick);
449
+ }
450
+ function stopLoop() {
451
+ if (handle !== null)
452
+ caf(handle);
453
+ handle = null;
454
+ last = -1;
455
+ stopBeat();
456
+ }
457
+ /** Nothing drawn for a while: no more frames asked for, the heartbeat instead. */
458
+ function sleep() {
459
+ asleep = true;
460
+ armBeat();
461
+ }
462
+ function armBeat() {
463
+ beatDue = now() + HEARTBEAT_MS;
464
+ beat = timer.set(onBeat, HEARTBEAT_MS);
465
+ }
466
+ function stopBeat() {
467
+ if (beat !== null)
468
+ timer.clear(beat);
469
+ beat = null;
470
+ asleep = false;
471
+ }
472
+ /** A heartbeat that ran over a freeze late: the main thread was held, timed as a frame from when it was due. */
473
+ function onBeat() {
474
+ beat = null;
475
+ if (now() - beatDue > FREEZE_MS)
476
+ wakeFrom(beatDue);
477
+ else
478
+ armBeat();
479
+ }
480
+ /** The page drew something new: the loop runs again, its first frame timed from `from`. */
481
+ function wakeFrom(from) {
482
+ if (disposed || doc.visibilityState === 'hidden')
483
+ return;
484
+ stopBeat();
485
+ lastWake = now();
486
+ last = from;
487
+ if (handle === null)
488
+ handle = raf(tick);
489
+ }
490
+ function onActivity() {
491
+ lastWake = now();
492
+ // A change made while the main thread was held past the heartbeat's due time is timed from that time.
493
+ if (asleep)
494
+ wakeFrom(Math.min(lastWake, beatDue));
495
+ }
496
+ function onVisibility() {
497
+ if (doc.visibilityState === 'hidden') {
498
+ stopLoop();
499
+ if (open)
500
+ closeStretch('hidden');
501
+ }
502
+ else
503
+ startLoop();
504
+ }
505
+ function summary(why) {
506
+ if (frames === 0)
507
+ return;
508
+ const p50 = percentile(histogram, frames, 0.5);
509
+ if (!envSent) {
510
+ envSent = true;
511
+ // The display's own rate, from this summary's own calm frames rather than a fresh sample: free.
512
+ host.report({ what: 'env', hz: Math.round(1000 / Math.max(1, p50)), ...env() });
513
+ }
514
+ host.report({
515
+ what: 'summary',
516
+ why,
517
+ fromTurn: summaryTurn,
518
+ turn: lastTurn,
519
+ frames,
520
+ watchedMs: Math.round(watchedMs),
521
+ fps: Math.round((frames * 10_000) / Math.max(1, watchedMs)) / 10,
522
+ p50,
523
+ p95: percentile(histogram, frames, 0.95),
524
+ p99: percentile(histogram, frames, 0.99),
525
+ worstMs: Math.round(worst),
526
+ stretches,
527
+ reports,
528
+ suppressed: suppressedTotal,
529
+ // The monitor's own cost per frame, in µs: what it adds to every frame it times.
530
+ selfUs: Math.round((selfMs * 100_000) / Math.max(1, selfFrames)) / 100,
531
+ attribution,
532
+ });
533
+ const byPhase = {};
534
+ for (const [name, p] of [...phases].sort((a, b) => b[1].frames - a[1].frames).slice(0, PHASE_FIELDS))
535
+ byPhase[name.slice(0, 32)] = phaseField(p);
536
+ host.report({ what: 'phases', ...byPhase });
537
+ phases.clear();
538
+ phaseNow = null;
539
+ histogram.fill(0);
540
+ frames = 0;
541
+ watchedMs = 0;
542
+ worst = 0;
543
+ selfMs = 0;
544
+ selfFrames = 0;
545
+ stretches = 0;
546
+ suppressedTotal = 0;
547
+ summaryTurn = lastTurn;
548
+ }
549
+ /** A tab closing runs no effect cleanup: what it saw is sent as it goes. */
550
+ function onPageHide() {
551
+ if (open)
552
+ closeStretch('end');
553
+ summary('end');
554
+ }
555
+ doc.addEventListener('visibilitychange', onVisibility);
556
+ win.addEventListener('pagehide', onPageHide);
557
+ const unwake = wakeOn(onActivity);
558
+ startLoop();
559
+ return {
560
+ noteTurn(turn) {
561
+ if (turn === lastTurn)
562
+ return;
563
+ lastTurn = turn;
564
+ if (summaryTurn < 0)
565
+ summaryTurn = turn;
566
+ else if (turn - summaryTurn >= SUMMARY_EVERY_TURNS)
567
+ summary('turns');
568
+ },
569
+ notePhase(next) {
570
+ if (next === phase)
571
+ return;
572
+ phase = next;
573
+ phaseNow = phases.get(next) ?? null;
574
+ },
575
+ noteGameOver() {
576
+ summary('over');
577
+ },
578
+ dispose() {
579
+ if (disposed)
580
+ return;
581
+ stopLoop();
582
+ disposed = true;
583
+ unwake();
584
+ doc.removeEventListener('visibilitychange', onVisibility);
585
+ win.removeEventListener('pagehide', onPageHide);
586
+ observer?.disconnect();
587
+ if (open)
588
+ closeStretch('end');
589
+ summary('end');
590
+ },
591
+ };
592
+ }
@@ -0,0 +1,8 @@
1
+ import { type ClientData, type PageEvent } from '@wolffm/platform-wire/telemetry';
2
+ import { type FrameWatchHost } from './frame-watch.js';
3
+ /** The watch's own seams a page may fill in: the game's quiet nodes and work meter, or a test's clock and frames. */
4
+ export type PageFrameSeams = Omit<FrameWatchHost, 'report' | 'board'>;
5
+ /** Send one `perf` event of `page`: kept alive past a closing tab, as the watch's last summary is sent then. */
6
+ export declare function sendPagePerf(page: PageEvent['page'], data: ClientData): void;
7
+ /** Watch this screen's frames while it is mounted and `on`; `facts` are read as a stretch opens, like a match's board. */
8
+ export declare function usePageFrames(page: PageEvent['page'], on: boolean, facts: () => ClientData, turn?: number, phase?: string, seams?: PageFrameSeams): void;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The frame rate of a screen with no match: a front page, a draft. The match's own watch
3
+ * (`./frame-watch.ts`: bad stretches, what was drawing in them, long frames attributed, a summary, the
4
+ * machine) runs unchanged; only where its events go differs. A match sends them over its socket into the
5
+ * play log; these pages have no match socket, so each event is a `perf` page event to `/api/client-events`
6
+ * (`PageEventSchema`), logged with the page it names and the user.
7
+ *
8
+ * `turn` and `phase` are the page's own clock and state, as a match's turn and phase are: a summary every few
9
+ * turns, and the frames split by phase. A draft passes its pick count and whether a pack is waiting.
10
+ */
11
+ import { useEffect, useRef } from 'react';
12
+ import { PAGE_EVENT_PATH } from '@wolffm/platform-wire/telemetry';
13
+ import { apiUrl, sendJson } from "../http.js";
14
+ import { watchFrames } from "./frame-watch.js";
15
+ /** Send one `perf` event of `page`: kept alive past a closing tab, as the watch's last summary is sent then. */
16
+ export function sendPagePerf(page, data) {
17
+ void sendJson(apiUrl(PAGE_EVENT_PATH), 'POST', { page, kind: 'perf', data }, undefined, { keepalive: true }).catch((err) => console.warn(`[${page}] could not report frames`, err));
18
+ }
19
+ /** Watch this screen's frames while it is mounted and `on`; `facts` are read as a stretch opens, like a match's board. */
20
+ export function usePageFrames(page, on, facts, turn, phase, seams = {}) {
21
+ const read = useRef(facts);
22
+ read.current = facts;
23
+ const host = useRef(seams);
24
+ host.current = seams;
25
+ const watch = useRef(null);
26
+ useEffect(() => {
27
+ if (!on)
28
+ return undefined;
29
+ const w = watchFrames({ ...host.current, report: (data) => sendPagePerf(page, data), board: () => read.current() });
30
+ watch.current = w;
31
+ return () => {
32
+ watch.current = null;
33
+ w.dispose();
34
+ };
35
+ }, [page, on]);
36
+ useEffect(() => {
37
+ if (turn !== undefined && turn >= 0)
38
+ watch.current?.noteTurn(turn);
39
+ }, [turn]);
40
+ useEffect(() => {
41
+ if (phase !== undefined)
42
+ watch.current?.notePhase(phase);
43
+ }, [phase]);
44
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A list's scroll smoothness, in the server's log: a scroll of the box that holds the list opens a
3
+ * burst; one frame loop (`everyFrame`) times the gap before every frame the list moved in, until it has
4
+ * been still for {@link IDLE_MS}, then sends one `perf` page event (platform-wire's `PageEventSchema`)
5
+ * summarising the burst: how many frames, their median and p95, how many ran over 25 ms (a 60 Hz frame
6
+ * dropped) and over 50 ms, with the browser, its version, the pixel ratio, the window and the room count.
7
+ *
8
+ * No per-frame upload: a frame costs a clock read and a histogram bump (`./frame-watch.ts`'s
9
+ * buckets), and a burst sends one event. Nothing runs while the list is not scrolling.
10
+ */
11
+ import type { PageEvent } from '@wolffm/platform-wire/telemetry';
12
+ import type { everyFrame } from '@wolffm/ui-shell/motion';
13
+ type Data = PageEvent['data'];
14
+ /**
15
+ * A burst is over once frames have gone by for this long without the list moving, timed by the
16
+ * frames' own start times. Not by the clock read inside a frame: that includes the frame's own work,
17
+ * so a scroll drawn at 300 ms a frame (a loaded Firefox, 40 rooms) read as still at every frame, each
18
+ * burst ended a frame long, and the slowest scrolls, the ones this exists for, sent nothing.
19
+ */
20
+ export declare const IDLE_MS = 250;
21
+ /** A burst still scrolling after this long is reported and the next scroll opens a new one. */
22
+ export declare const MAX_BURST_MS = 10000;
23
+ /**
24
+ * A burst whose moving frames span less than this is a nudge, not a scroll: nothing is sent. Ten
25
+ * frames at 60 Hz, as time and not a count of frames, so a scroll drawn at a few frames a second
26
+ * still counts.
27
+ */
28
+ export declare const MIN_SCROLL_MS = 160;
29
+ /** A gap over this is a dropped frame at 60 Hz: one and a half frames. */
30
+ export declare const DROP_MS = 25;
31
+ /** A gap over this is two frames missed in a row. */
32
+ export declare const SLOW_MS = 50;
33
+ /** At most this many bursts reported per page: a long session must not turn its telemetry into traffic. */
34
+ export declare const MAX_REPORTS = 30;
35
+ export interface ScrollWatchHost {
36
+ readonly win: Pick<Window, 'devicePixelRatio' | 'innerWidth' | 'innerHeight'>;
37
+ readonly frame: typeof everyFrame;
38
+ readonly doc: Pick<Document, 'addEventListener' | 'removeEventListener'>;
39
+ readonly now: () => number;
40
+ readonly userAgent: string;
41
+ /** Whether a scroll of this target moves the room list. */
42
+ readonly scrolls: (target: EventTarget | null) => boolean;
43
+ /** How many rooms the list draws now. */
44
+ readonly rooms: () => number;
45
+ readonly ui: string;
46
+ readonly send: (data: Data) => void;
47
+ }
48
+ /** The browser family and its major version, from the user agent; `other` when it names none we know. */
49
+ export declare function browserOf(ua: string): {
50
+ browser: string;
51
+ version: number;
52
+ };
53
+ /** Start watching; returns the stop. A burst still open when it stops is reported. */
54
+ export declare function watchScroll(host: ScrollWatchHost): () => void;
55
+ export {};
@@ -0,0 +1,125 @@
1
+ import { BUCKETS, bucketOf, percentile } from "./frame-watch.js";
2
+ /**
3
+ * A burst is over once frames have gone by for this long without the list moving, timed by the
4
+ * frames' own start times. Not by the clock read inside a frame: that includes the frame's own work,
5
+ * so a scroll drawn at 300 ms a frame (a loaded Firefox, 40 rooms) read as still at every frame, each
6
+ * burst ended a frame long, and the slowest scrolls, the ones this exists for, sent nothing.
7
+ */
8
+ export const IDLE_MS = 250;
9
+ /** A burst still scrolling after this long is reported and the next scroll opens a new one. */
10
+ export const MAX_BURST_MS = 10_000;
11
+ /**
12
+ * A burst whose moving frames span less than this is a nudge, not a scroll: nothing is sent. Ten
13
+ * frames at 60 Hz, as time and not a count of frames, so a scroll drawn at a few frames a second
14
+ * still counts.
15
+ */
16
+ export const MIN_SCROLL_MS = 160;
17
+ /** A gap over this is a dropped frame at 60 Hz: one and a half frames. */
18
+ export const DROP_MS = 25;
19
+ /** A gap over this is two frames missed in a row. */
20
+ export const SLOW_MS = 50;
21
+ /** At most this many bursts reported per page: a long session must not turn its telemetry into traffic. */
22
+ export const MAX_REPORTS = 30;
23
+ /** The browser family and its major version, from the user agent; `other` when it names none we know. */
24
+ export function browserOf(ua) {
25
+ const families = [
26
+ ['firefox', /Firefox\/(\d+)/],
27
+ ['edge', /Edg\/(\d+)/],
28
+ ['opera', /OPR\/(\d+)/],
29
+ ['chrome', /Chrome\/(\d+)/],
30
+ ['safari', /Version\/(\d+).*Safari\//],
31
+ ];
32
+ for (const [browser, re] of families) {
33
+ const m = re.exec(ua);
34
+ if (m !== null)
35
+ return { browser, version: Number(m[1]) };
36
+ }
37
+ return { browser: 'other', version: 0 };
38
+ }
39
+ /** Start watching; returns the stop. A burst still open when it stops is reported. */
40
+ export function watchScroll(host) {
41
+ const { browser, version } = browserOf(host.userAgent);
42
+ const histogram = new Uint32Array(BUCKETS);
43
+ let frames = 0;
44
+ let over25 = 0;
45
+ let over50 = 0;
46
+ let max = 0;
47
+ let startedAt = 0;
48
+ let prevFrame = null;
49
+ /** The start of the burst's first frame, and of the last frame the list moved in. */
50
+ let firstAt = 0;
51
+ let movedAt = 0;
52
+ /** Whether the list scrolled since the last frame: the still frames that end a burst are not counted. */
53
+ let moved = false;
54
+ let stop = null;
55
+ let reports = 0;
56
+ const end = () => {
57
+ stop?.();
58
+ stop = null;
59
+ if (frames > 0 && movedAt - firstAt >= MIN_SCROLL_MS && reports < MAX_REPORTS) {
60
+ reports += 1;
61
+ host.send({
62
+ what: 'scroll',
63
+ frames,
64
+ ms: Math.round(host.now() - startedAt),
65
+ p50: percentile(histogram, frames, 0.5),
66
+ p95: percentile(histogram, frames, 0.95),
67
+ max: Math.round(max),
68
+ over25,
69
+ over50,
70
+ browser,
71
+ version,
72
+ dpr: Math.round(host.win.devicePixelRatio * 100) / 100,
73
+ vw: host.win.innerWidth,
74
+ vh: host.win.innerHeight,
75
+ rooms: host.rooms(),
76
+ ui: host.ui,
77
+ });
78
+ }
79
+ histogram.fill(0);
80
+ frames = 0;
81
+ over25 = 0;
82
+ over50 = 0;
83
+ max = 0;
84
+ prevFrame = null;
85
+ };
86
+ const tick = (t) => {
87
+ if (prevFrame !== null && moved) {
88
+ const gap = t - prevFrame;
89
+ histogram[bucketOf(gap)] += 1;
90
+ frames += 1;
91
+ if (gap > DROP_MS)
92
+ over25 += 1;
93
+ if (gap > SLOW_MS)
94
+ over50 += 1;
95
+ if (gap > max)
96
+ max = gap;
97
+ }
98
+ if (prevFrame === null)
99
+ firstAt = t;
100
+ if (moved || prevFrame === null)
101
+ movedAt = t;
102
+ prevFrame = t;
103
+ moved = false;
104
+ if (t - movedAt <= IDLE_MS && host.now() - startedAt <= MAX_BURST_MS)
105
+ return () => undefined;
106
+ end();
107
+ return null;
108
+ };
109
+ const onScroll = (e) => {
110
+ if (!host.scrolls(e.target))
111
+ return;
112
+ moved = true;
113
+ if (stop !== null)
114
+ return;
115
+ startedAt = host.now();
116
+ stop = host.frame(tick);
117
+ };
118
+ // `scroll` does not bubble from an element: caught on the way down instead, from whichever box scrolls.
119
+ host.doc.addEventListener('scroll', onScroll, { capture: true, passive: true });
120
+ return () => {
121
+ host.doc.removeEventListener('scroll', onScroll, { capture: true });
122
+ if (stop !== null)
123
+ end();
124
+ };
125
+ }
@@ -0,0 +1,34 @@
1
+ export interface PointerPresenceOptions<P, M> {
2
+ readonly periodMs: number;
3
+ readonly restateMs: number;
4
+ readonly staleMs: number;
5
+ readonly transport: {
6
+ send(message: M): void;
7
+ };
8
+ /** This seat's message with its pointer at `pointer`, the rest read now; null when it has nothing to say. */
9
+ readonly compose: (pointer: P | null) => M | null;
10
+ /** Whether `message` says something stands parked, to be said again every `restateMs`. */
11
+ readonly parked: (message: M) => boolean;
12
+ /** The peer's pointer comes down: stale or idle. */
13
+ readonly takeDown: () => void;
14
+ /** Where the page says it is hidden: the real `document` by default. */
15
+ readonly doc?: Pick<Document, 'visibilityState' | 'addEventListener' | 'removeEventListener'>;
16
+ }
17
+ export declare function pointerPresence<P, M>(options: PointerPresenceOptions<P, M>): {
18
+ /** The pointer is at `at` (null: it left): sent within the period, the latest winning. */
19
+ move(at: P | null): void;
20
+ /** Sent now, outside the period, composed at the last pointer; still never a repeat. */
21
+ flush: () => void;
22
+ /** `message` out now, a repeat or not, the move due dropped; `at`, when given, is the last pointer from now on. */
23
+ say(message: M, at?: P): void;
24
+ readonly pointer: P | null;
25
+ /** The peer drawn is `seat`'s, heard from now: it comes down after the stale time with no word. */
26
+ receive(seat: number): void;
27
+ /** The seat whose pointer is drawn, or null. */
28
+ readonly drawn: number | null;
29
+ /** The drawn pointer came down: its seat and its stale clock are forgotten. */
30
+ forget(): void;
31
+ /** Takes the drawn pointer down when `still(seat)` says that seat is no longer the one drawn. */
32
+ dropIdle(still: (seat: number) => boolean): void;
33
+ dispose(): void;
34
+ };
@@ -0,0 +1,97 @@
1
+ /*
2
+ * A seat's pointer, shared with the other screens of a game, and the other seats' pointers on this one.
3
+ * The game says what a message is and draws what it hears; this owns when a message goes and when a
4
+ * peer's pointer comes down. A move is sent at most once a period, the latest winning, composed when it
5
+ * goes so it says what the page shows then; a repeat of the last message (by its JSON) is never sent
6
+ * unless said outright; a parked message is said again every restate period while it stands, so a play
7
+ * still being decided reaches the other screen with the pointer at rest; a hidden page says `null`. A
8
+ * peer heard nothing from for the stale time comes down, and so does one the game no longer draws.
9
+ */
10
+ import { throttle } from "./throttle.js";
11
+ export function pointerPresence(options) {
12
+ const doc = options.doc ?? document;
13
+ let pointer = null;
14
+ let last = null;
15
+ let restate = null;
16
+ let drawn = null;
17
+ let stale = null;
18
+ /** `message`, out now; a repeat of the last one only when `again`. Whether it went. */
19
+ function emit(message, again) {
20
+ const key = JSON.stringify(message);
21
+ if (key === last && !again)
22
+ return false;
23
+ last = key;
24
+ moves.sent();
25
+ options.transport.send(message);
26
+ if (restate !== null)
27
+ clearTimeout(restate);
28
+ restate = !options.parked(message) ? null : setTimeout(restateNow, options.restateMs);
29
+ return true;
30
+ }
31
+ function restateNow() {
32
+ restate = null;
33
+ last = null;
34
+ sendAt(pointer);
35
+ }
36
+ const sendAt = (at) => {
37
+ const message = options.compose(at);
38
+ return message !== null && emit(message, false);
39
+ };
40
+ const moves = throttle(options.periodMs, () => sendAt(pointer), { deferred: true });
41
+ const onVisibility = () => {
42
+ if (doc.visibilityState === 'hidden')
43
+ presence.move(null);
44
+ };
45
+ doc.addEventListener('visibilitychange', onVisibility);
46
+ const presence = {
47
+ /** The pointer is at `at` (null: it left): sent within the period, the latest winning. */
48
+ move(at) {
49
+ pointer = at;
50
+ moves.soon();
51
+ },
52
+ /** Sent now, outside the period, composed at the last pointer; still never a repeat. */
53
+ flush: () => moves.flush(),
54
+ /** `message` out now, a repeat or not, the move due dropped; `at`, when given, is the last pointer from now on. */
55
+ say(message, at) {
56
+ moves.cancel();
57
+ if (at !== undefined)
58
+ pointer = at;
59
+ emit(message, true);
60
+ },
61
+ get pointer() {
62
+ return pointer;
63
+ },
64
+ /** The peer drawn is `seat`'s, heard from now: it comes down after the stale time with no word. */
65
+ receive(seat) {
66
+ drawn = seat;
67
+ if (stale !== null)
68
+ clearTimeout(stale);
69
+ stale = setTimeout(options.takeDown, options.staleMs);
70
+ },
71
+ /** The seat whose pointer is drawn, or null. */
72
+ get drawn() {
73
+ return drawn;
74
+ },
75
+ /** The drawn pointer came down: its seat and its stale clock are forgotten. */
76
+ forget() {
77
+ drawn = null;
78
+ if (stale !== null)
79
+ clearTimeout(stale);
80
+ stale = null;
81
+ },
82
+ /** Takes the drawn pointer down when `still(seat)` says that seat is no longer the one drawn. */
83
+ dropIdle(still) {
84
+ if (drawn !== null && !still(drawn))
85
+ options.takeDown();
86
+ },
87
+ dispose() {
88
+ doc.removeEventListener('visibilitychange', onVisibility);
89
+ moves.cancel();
90
+ if (restate !== null)
91
+ clearTimeout(restate);
92
+ restate = null;
93
+ presence.forget();
94
+ },
95
+ };
96
+ return presence;
97
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-ui",
3
- "version": "0.1.271",
4
- "gitHead": "f035aa0cf055c6e343babfa162040e2e407c16a7",
3
+ "version": "0.1.272",
4
+ "gitHead": "6269de09a79b1555f2d0f24ed2ff8c1857520990",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The browser parts any hosted game shares, above ui-shell: the room shell and session, seats and looks, the room route, the front page's generic pieces (gate, polls, gallery, patch notes), the bundle slot and relay channel a game's client mounts in, settings and trim screens, the HTTP and socket helpers, and the generic components (modal, popover, avatar, action button, radio cards). Knows no game; Magic's UI (games/magic/ui) plugs in, composed by the site (apps/ui). MIT; imports only react, react-dom, socket.io-client, @wolffm/* and the platform packages.",
@@ -53,8 +53,8 @@
53
53
  "react-dom": "^19.2.8"
54
54
  },
55
55
  "dependencies": {
56
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.275",
57
- "@wolffm/ui-shell": "npm:@hadoku/ui-shell@0.1.275",
56
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.276",
57
+ "@wolffm/ui-shell": "npm:@hadoku/ui-shell@0.1.276",
58
58
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.4",
59
59
  "@wolffm/rooms-client": "npm:@hadoku/rooms-client@^0.45.159",
60
60
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.159",