nitro-react/src/hooks/useSharedVisibility.ts

45 lines
972 B
TypeScript
Raw Normal View History

2022-03-30 16:19:09 +02:00
import { useCallback, useMemo, useState } from 'react';
export const useSharedVisibility = () =>
{
const [ activeIds, setActiveIds ] = useState<number[]>([]);
const isVisible = useMemo(() => !!activeIds.length, [ activeIds ]);
const activate = useCallback(() =>
{
let id = -1;
setActiveIds(prevValue =>
2022-04-01 22:12:46 +02:00
{
const newValue = [ ...prevValue ];
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
id = newValue.length ? (newValue[(newValue.length - 1)] + 1) : 0;
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
newValue.push(id);
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
return newValue;
});
2022-03-30 16:19:09 +02:00
return id;
}, []);
const deactivate = useCallback((id: number) =>
{
setActiveIds(prevValue =>
2022-04-01 22:12:46 +02:00
{
const newValue = [ ...prevValue ];
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
const index = newValue.indexOf(id);
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
if(index === -1) return prevValue;
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
newValue.splice(index, 1);
2022-03-30 16:19:09 +02:00
2022-04-01 22:12:46 +02:00
return newValue;
});
2022-03-30 16:19:09 +02:00
}, []);
return { isVisible, activate, deactivate };
}