@atlaskit/editor-core
Version:
A package contains Atlassian editor core functionality
61 lines (58 loc) • 2.23 kB
JavaScript
import { useEffect } from 'react';
import debounce from 'lodash/debounce';
import { useAnalyticsEvents } from '@atlaskit/analytics-next/useAnalyticsEvents';
import { ACTION_SUBJECT, EVENT_TYPE, fireAnalyticsEvent } from '@atlaskit/editor-common/analytics';
import { setupINPTracking } from '@atlaskit/editor-performance-metrics/inp';
import { getActiveInteraction } from '@atlaskit/react-ufo/interaction-metrics';
export const EditorINPMetrics = () => {
const analyticsEvents = useAnalyticsEvents();
// onMount lifecycle hook
useEffect(() => {
let cleanupFn;
const cleanupIdleCallback = createIdleCallback(() => {
cleanupFn = setupINPTracking(({
value
}) => {
const interaction = getActiveInteraction();
const ufoName = interaction === null || interaction === void 0 ? void 0 : interaction.ufoName;
sendAnalytics(analyticsEvents.createAnalyticsEvent, value, ufoName);
});
});
// Cleanup function that will be called when the component unmounts
return () => {
var _cleanupFn;
cleanupIdleCallback();
(_cleanupFn = cleanupFn) === null || _cleanupFn === void 0 ? void 0 : _cleanupFn();
};
// Using hook as mount lifecycle hook.
// We do not need to set dependency on analyticsEvents since we are using the analyticsEvents object reference
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// This component doesn't render anything
return null;
};
const sendAnalytics = debounce((createAnalyticsEvent, value, ufoName) => {
fireAnalyticsEvent(createAnalyticsEvent)({
payload: {
// @ts-expect-error Temporary data
action: 'inp',
actionSubject: ACTION_SUBJECT.EDITOR,
eventType: EVENT_TYPE.TRACK,
attributes: {
inp: value,
ufoName
}
}
});
}, 1_000, {
trailing: true
});
const createIdleCallback = callback => {
if (typeof window.requestIdleCallback === 'function') {
const id = window.requestIdleCallback(callback);
return () => window.cancelIdleCallback(id);
}
// Fallback to setTimeout with 0 delay if requestIdleCallback is not available
const id = window.setTimeout(callback, 0);
return () => window.clearTimeout(id);
};