-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.perf.mjs
More file actions
266 lines (236 loc) · 7.42 KB
/
util.perf.mjs
File metadata and controls
266 lines (236 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
* @fileoverview Performance Utilities - FPS tracking, scroll snap detection, easing
* @module util.perf
* @version 1.1.0
* @author hnldesign
* @since 2022
*/
export const NAME = 'perf';
/**
* Timeout threshold for scroll stop detection.
* @private
* @constant {number}
*/
const SCROLL_STOP_TIMEOUT = 150;
/**
* FPS calculation window in milliseconds.
* @private
* @constant {number}
*/
const FPS_WINDOW = 1000;
/**
* Adds scroll snap detection to an element.
* Dispatches scrollSnapped, scrollStopped, and scrollStoppedSnapped events.
*
* Requires data-scroll-direction="horizontal|vertical" on element.
*
* @param {HTMLElement} element - Snap-scrolling element
* @param {Object} [options={}] - Configuration options
* @param {Function} [options.onSnap] - Callback when snapping occurs
* @param {Function} [options.onStop] - Callback when scrolling stops
* @param {number} [options.stopTimeout=150] - Timeout for stop detection (ms)
*
* @example
* const scroller = document.querySelector('.snap-scroller');
* snapScrollComplete(scroller, {
* onSnap: () => console.log('Snapped to position'),
* onStop: () => console.log('Scroll stopped'),
* stopTimeout: 200
* });
*/
export function snapScrollComplete(element, options = {}) {
const {
onSnap = null,
onStop = null,
stopTimeout = SCROLL_STOP_TIMEOUT
} = options;
if (!element.dataset.scrollDirection) {
console.warn('snapScrollComplete: element requires data-scroll-direction attribute');
return;
}
const isHorizontal = element.dataset.scrollDirection === 'horizontal';
let timeout = null;
const handler = (e) => {
const scrollPos = isHorizontal ? e.target.scrollLeft : e.target.scrollTop;
const dimension = isHorizontal ? e.target.offsetWidth : e.target.offsetHeight;
const atSnappingPoint = scrollPos % dimension === 0;
const delay = atSnappingPoint ? 0 : stopTimeout;
clearTimeout(timeout);
timeout = setTimeout(() => {
if (!delay) {
e.target.dispatchEvent(new Event('scrollSnapped'));
if (typeof onSnap === 'function') onSnap.call(element);
} else {
e.target.dispatchEvent(new Event('scrollStopped'));
if (typeof onStop === 'function') onStop.call(element);
}
e.target.dispatchEvent(new Event('scrollStoppedSnapped'));
}, delay);
};
element.addEventListener('scroll', handler, {passive: true});
// Return cleanup function
return () => {
clearTimeout(timeout);
element.removeEventListener('scroll', handler);
};
}
/**
* FPS (frames per second) counter with event dispatching.
* Measures real-time FPS and dispatches fpsUpdate events.
*
* @class
*
* @example
* const fpsCounter = new FpsCounter((fps) => {
* console.log(`Current FPS: ${fps}`);
* });
*
* // Later, stop tracking
* fpsCounter.stop();
*
* @example
* // Listen to events instead of callback
* const counter = new FpsCounter();
* window.addEventListener('fpsUpdate', (e) => {
* console.log('FPS:', e.detail.fps);
* });
*/
export class FpsCounter {
/**
* Creates FPS counter instance.
*
* @param {Function} [callback] - Called on each FPS update with current FPS value
*/
constructor(callback) {
this.timeStamps = [performance.now()];
this.fpsEvent = new CustomEvent('fpsUpdate', {detail: this, bubbles: true, cancelable: true});
this.callback = typeof callback === 'function' ? callback : null;
this.fps = 60; // Default assumption
this.requestId = null;
this.fpsTimer = this.fpsTimer.bind(this);
this.start();
}
/**
* Internal timer for FPS calculation.
* @private
* @param {DOMHighResTimeStamp} now - Current timestamp
*/
fpsTimer(now) {
// Keep only timestamps within last second
this.timeStamps = this.timeStamps.filter((time) => (now - time) <= FPS_WINDOW);
// Calculate real-time FPS
const len = this.timeStamps.length;
this.realFPS = len > 1 ? (1000 / (now - this.timeStamps[len - 1])) : this.fps;
// Add current timestamp
this.timeStamps.push(now);
// Average bucket count with real FPS (smooths out frame drops)
this.fps = Math.round((this.timeStamps.length + this.realFPS) / 2);
// Dispatch event
window.dispatchEvent(this.fpsEvent);
// Execute callback
if (this.callback) {
this.callback.call(this, this.fps);
}
// Continue loop
this.requestId = requestAnimationFrame(this.fpsTimer);
}
/**
* Starts FPS counter.
* @public
*/
start() {
if (!this.requestId) {
this.requestId = requestAnimationFrame(this.fpsTimer);
}
}
/**
* Stops FPS counter and cleans up resources.
* @public
*/
stop() {
if (this.requestId) {
cancelAnimationFrame(this.requestId);
this.requestId = null;
}
}
}
/**
* Calculates eased mean values for smoothing data streams.
* Maintains separate histories per type for multiple concurrent streams.
*
* @class
*
* @example
* const easer = new EasedMeanCalculator();
*
* // Smooth scroll speed over 5 frames
* const smoothSpeed = easer.getValue(currentSpeed, 'speed', 5);
*
* // Smooth FPS over 3 frames
* const smoothFps = easer.getValue(currentFps, 'fps', 3);
*
* // Reset specific stream
* easer.reset('speed');
*/
export class EasedMeanCalculator {
/**
* Creates easing calculator instance.
*/
constructor() {
this.history = {};
}
/**
* Gets eased mean value for a data stream.
*
* @param {number} value - Current value to add to history
* @param {string} [type='default'] - Stream identifier
* @param {number} [range=3] - Number of values to average
* @returns {number} Eased mean value
*/
getValue(value, type = 'default', range = 3) {
// Initialize history for type
if (!this.history[type]) {
this.history[type] = [];
}
// Add current value
this.history[type].push(value);
// Use only last N values
const recent = this.history[type].slice(-range);
// Calculate mean
return recent.reduce((sum, val) => sum + val, 0) / recent.length;
}
/**
* Resets history for a specific stream.
*
* @param {string} type - Stream identifier to reset
*/
reset(type) {
this.history[type] = [];
}
}
/**
* Calculates scroll percentage of webpage.
*
* @returns {number} Scroll percentage (0-100)
*
* @example
* window.addEventListener('scroll', () => {
* const pct = pageScrollPercentage();
* console.log(`Scrolled ${pct.toFixed(1)}%`);
* });
*/
export function pageScrollPercentage() {
const scrollPos = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;
let totalHeight = document.documentElement.scrollHeight - window.innerHeight;
// iOS Safari fix: if calculation seems wrong, use body height
if (totalHeight <= 0 || totalHeight < scrollPos) {
totalHeight = Math.max(
document.body.scrollHeight - window.innerHeight,
scrollPos // At minimum, we know we've scrolled this far
);
}
if (totalHeight <= 0) {
return 100;
}
return Math.min(100, Math.max(0, (scrollPos / totalHeight) * 100));
}