Files
react-native/Libraries/WebPerformance/EventCounts.js
T
Ruslan Shestopalyuk 581357bc9b Implement EventCounts Web Performance API for React Native (#36181)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36181

[Changelog][Internal]

Implements EventCounts API (`Performance.eventCounts`) for Web Performance, according to the W3C standard, see the specs here: https://www.w3.org/TR/event-timing/#eventcounts

The rationale for why we need it is to support some advanced metrics computations, such as a ratio of "slow events" to total event count, per event type.

Reviewed By: rubennorte

Differential Revision: D43285073

fbshipit-source-id: 2c53d04d9a57c1301e37f2a5879072c8d33efbbf
2023-02-16 06:21:43 -08:00

79 lines
2.1 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
import NativePerformanceObserver from './NativePerformanceObserver';
import {warnNoNativePerformanceObserver} from './PerformanceObserver';
type EventCountsForEachCallbackType =
| (() => void)
| ((value: number) => void)
| ((value: number, key: string) => void)
| ((value: number, key: string, map: Map<string, number>) => void);
let cachedEventCounts: ?Map<string, number>;
function getCachedEventCounts(): Map<string, number> {
if (cachedEventCounts) {
return cachedEventCounts;
}
if (!NativePerformanceObserver) {
warnNoNativePerformanceObserver();
return new Map();
}
cachedEventCounts = new Map<string, number>(
NativePerformanceObserver.getEventCounts(),
);
// $FlowFixMe[incompatible-call]
global.queueMicrotask(() => {
// To be consistent with the calls to the API from the same task,
// but also not to refetch the data from native too often,
// schedule to invalidate the cache later,
// after the current task is guaranteed to have finished.
cachedEventCounts = null;
});
return cachedEventCounts ?? new Map();
}
/**
* Implementation of the EventCounts Web Performance API
* corresponding to the standard in
* https://www.w3.org/TR/event-timing/#eventcounts
*/
export default class EventCounts {
// flowlint unsafe-getters-setters:off
get size(): number {
return getCachedEventCounts().size;
}
entries(): Iterator<[string, number]> {
return getCachedEventCounts().entries();
}
forEach(callback: EventCountsForEachCallbackType): void {
return getCachedEventCounts().forEach(callback);
}
get(key: string): ?number {
return getCachedEventCounts().get(key);
}
has(key: string): boolean {
return getCachedEventCounts().has(key);
}
keys(): Iterator<string> {
return getCachedEventCounts().keys();
}
values(): Iterator<number> {
return getCachedEventCounts().values();
}
}