tududi/frontend/hooks/usePersistedModal.ts
Chris 9d2b1895af
Feat/add project states (#354)
* Scaffold project states

* fixup! Scaffold project states

* Fix blinking project modal

* fixup! Fix blinking project modal

* fixup! fixup! Fix blinking project modal

* Fix an issue with the tag input autosuggest

* fixup! Fix an issue with the tag input autosuggest

* fixup! fixup! Fix an issue with the tag input autosuggest

* Add state to project details

* fixup! Add state to project details

* Add state indicator on project cards

* fixup! Add state indicator on project cards
2025-09-29 16:04:25 +03:00

78 lines
2.1 KiB
TypeScript

import { useState, useEffect, useRef } from 'react';
interface PersistedModalState {
isOpen: boolean;
projectId?: number;
timestamp?: number;
}
const MODAL_STATE_KEY = 'project-modal-state';
const MODAL_TIMEOUT = 5000; // 5 seconds timeout to prevent stale states
export const usePersistedModal = (projectId?: number) => {
const [isOpen, setIsOpen] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout>();
// Load persisted state on mount
useEffect(() => {
const savedState = sessionStorage.getItem(MODAL_STATE_KEY);
if (savedState) {
try {
const state: PersistedModalState = JSON.parse(savedState);
const now = Date.now();
// Check if state is recent and for the same project
if (
state.timestamp &&
now - state.timestamp < MODAL_TIMEOUT &&
state.projectId === projectId &&
state.isOpen
) {
setIsOpen(true);
}
} catch (error) {
console.error('Error parsing modal state:', error);
}
}
}, [projectId]);
// Clear timeout on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
const openModal = () => {
const state: PersistedModalState = {
isOpen: true,
projectId,
timestamp: Date.now(),
};
sessionStorage.setItem(MODAL_STATE_KEY, JSON.stringify(state));
setIsOpen(true);
// Clear the persisted state after timeout
timeoutRef.current = setTimeout(() => {
sessionStorage.removeItem(MODAL_STATE_KEY);
}, MODAL_TIMEOUT);
};
const closeModal = () => {
sessionStorage.removeItem(MODAL_STATE_KEY);
setIsOpen(false);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
return {
isOpen,
openModal,
closeModal,
};
};