Compare commits

...

1 Commits

Author SHA1 Message Date
achichenkov
9d1305ac66 fix(Map): add event collecting and reseting map state if more than limit 2025-03-04 16:38:33 +03:00
2 changed files with 38 additions and 11 deletions

View File

@@ -1,13 +1,10 @@
import { useState, useEffect } from 'react';
function usePageVisibility() {
export const usePageVisibility = () => {
const [isVisible, setIsVisible] = useState(!document.hidden);
useEffect(() => {
const handleVisibilityChange = () => {
setIsVisible(!document.hidden);
};
const handleVisibilityChange = () => setIsVisible(!document.hidden);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
@@ -16,6 +13,4 @@ function usePageVisibility() {
}, []);
return isVisible;
}
export default usePageVisibility;
};

View File

@@ -1,9 +1,21 @@
import { RefObject, useCallback } from 'react';
import { RefObject, useCallback, useEffect, useRef } from 'react';
import { MapHandlers } from '@/hooks/Mapper/types/mapHandlers.ts';
import { usePageVisibility } from '@/hooks/Mapper/hooks';
const COLLECTING_COUNT_EVENT_LIMIT = 100;
type MapEventIn = { type: never; body: never };
export const useMapperHandlers = (handlerRefs: RefObject<MapHandlers>[], hooksRef: RefObject<any>) => {
const isVisible = usePageVisibility();
const isVisibleRef = useRef(isVisible);
isVisibleRef.current = isVisible;
const eventsCollectorRef = useRef<MapEventIn[]>([]);
const handleCommand = useCallback(
// @ts-ignore
async ({ type, data }) => {
if (!hooksRef.current) {
return;
@@ -14,7 +26,12 @@ export const useMapperHandlers = (handlerRefs: RefObject<MapHandlers>[], hooksRe
[hooksRef.current],
);
const handleMapEvent = useCallback(({ type, body }) => {
const handleMapEvent = useCallback(({ type, body }: MapEventIn) => {
if (!isVisibleRef.current) {
eventsCollectorRef.current.push({ type, body });
return;
}
handlerRefs.forEach(ref => {
if (!ref.current) {
return;
@@ -25,7 +42,7 @@ export const useMapperHandlers = (handlerRefs: RefObject<MapHandlers>[], hooksRe
}, []);
const handleMapEvents = useCallback(
events => {
(events: MapEventIn[]) => {
events.forEach(event => {
handleMapEvent(event);
});
@@ -33,5 +50,20 @@ export const useMapperHandlers = (handlerRefs: RefObject<MapHandlers>[], hooksRe
[handleMapEvent],
);
useEffect(() => {
if (!isVisible || eventsCollectorRef.current.length === 0) {
return;
}
if (eventsCollectorRef.current.length >= COLLECTING_COUNT_EVENT_LIMIT) {
handleCommand({ type: 'force_reset', data: {} });
eventsCollectorRef.current = [];
return;
}
handleMapEvents([...eventsCollectorRef.current]);
eventsCollectorRef.current = [];
}, [handleCommand, handleMapEvents, isVisible]);
return { handleCommand, handleMapEvent, handleMapEvents };
};