Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 66x | import React, { createContext, ReactNode, ReactElement, useCallback, useRef } from 'react';
/**
* Interface for the context value
*/
interface ModalLockContextType {
acquireLock: () => number;
releaseLock: (id: number) => void;
hasLock: (id: number) => boolean;
}
/**
* Create the context with default values
*/
const ModalLockContext = createContext<ModalLockContextType>({
acquireLock: () => 0,
releaseLock: () => {/* No action need */ },
hasLock: () => false,
});
/**
* Interface for the provider props
*/
interface ModalLockProviderProps {
children: ReactNode; // React children elements
}
/**
* The provider component for the modal lock context
* @param {ModalLockProviderProps} props - The props for the provider component
* @returns {ReactElement} The provider element
*/
export function ModalLockProvider({ children }: ModalLockProviderProps): ReactElement {
const lockIdStackRef = useRef<number[]>([]);
const nextLockIdRef = useRef(1);
const acquireLock = useCallback(() => {
const newLockId = nextLockIdRef.current;
nextLockIdRef.current += 1;
lockIdStackRef.current.push(newLockId);
return newLockId;
}, []);
const releaseLock = useCallback((id: number) => {
const lockIdStack = lockIdStackRef.current;
if (lockIdStack.length > 0 && lockIdStack[lockIdStack.length - 1] === id) {
lockIdStack.pop();
} else {
console.error(`Attempted to release a non-top lock: ${id}`);
}
}, []);
const hasLock = useCallback((id: number) => {
const lockIdStack = lockIdStackRef.current;
return lockIdStack.length > 0 && lockIdStack[lockIdStack.length - 1] === id;
}, []);
return (
<ModalLockContext.Provider
value={{
acquireLock,
releaseLock,
hasLock,
}}
>
{children}
</ModalLockContext.Provider>
);
}
export default ModalLockContext;
|