Improve the frontend modals
This commit is contained in:
@@ -260,6 +260,13 @@ export interface AddModalProps {
|
||||
|
||||
// Field change callback for dynamic form behavior
|
||||
onFieldChange?: (fieldName: string, value: any) => void;
|
||||
|
||||
// Wait-for-refetch support (Option A approach)
|
||||
waitForRefetch?: boolean; // Enable wait-for-refetch behavior after save
|
||||
isRefetching?: boolean; // External refetch state (from React Query)
|
||||
onSaveComplete?: () => Promise<void>; // Async callback for triggering refetch
|
||||
refetchTimeout?: number; // Timeout in ms for refetch (default: 3000)
|
||||
showSuccessState?: boolean; // Show brief success state before closing (default: true)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,9 +296,18 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
validationErrors = EMPTY_VALIDATION_ERRORS,
|
||||
onValidationError,
|
||||
onFieldChange,
|
||||
// Wait-for-refetch support
|
||||
waitForRefetch = false,
|
||||
isRefetching = false,
|
||||
onSaveComplete,
|
||||
refetchTimeout = 3000,
|
||||
showSuccessState = true,
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<Record<string, any>>({});
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [isWaitingForRefetch, setIsWaitingForRefetch] = useState(false);
|
||||
const [showSuccess, setShowSuccess] = useState(false);
|
||||
const { t } = useTranslation(['common']);
|
||||
|
||||
// Track if we've initialized the form data for this modal session
|
||||
@@ -337,6 +353,15 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
};
|
||||
|
||||
const handleFieldChange = (fieldName: string, value: string | number) => {
|
||||
// Debug logging for ingredients field
|
||||
if (fieldName === 'ingredients') {
|
||||
console.log('=== AddModal Field Change (ingredients) ===');
|
||||
console.log('New value:', value);
|
||||
console.log('Type:', typeof value);
|
||||
console.log('Is array:', Array.isArray(value));
|
||||
console.log('==========================================');
|
||||
}
|
||||
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[fieldName]: value
|
||||
@@ -406,11 +431,62 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
|
||||
// Execute the save mutation
|
||||
await onSave(formData);
|
||||
|
||||
// If waitForRefetch is enabled, wait for data to refresh
|
||||
if (waitForRefetch && onSaveComplete) {
|
||||
setIsWaitingForRefetch(true);
|
||||
|
||||
// Trigger the refetch
|
||||
await onSaveComplete();
|
||||
|
||||
// Wait for isRefetching to become true then false, or timeout
|
||||
const startTime = Date.now();
|
||||
const checkRefetch = () => {
|
||||
return new Promise<void>((resolve) => {
|
||||
const interval = setInterval(() => {
|
||||
const elapsed = Date.now() - startTime;
|
||||
|
||||
// Timeout reached
|
||||
if (elapsed >= refetchTimeout) {
|
||||
clearInterval(interval);
|
||||
console.warn('Refetch timeout reached, proceeding anyway');
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
// Refetch completed (was true, now false)
|
||||
if (!isRefetching) {
|
||||
clearInterval(interval);
|
||||
resolve();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
};
|
||||
|
||||
await checkRefetch();
|
||||
setIsWaitingForRefetch(false);
|
||||
|
||||
// Show success state briefly
|
||||
if (showSuccessState) {
|
||||
setShowSuccess(true);
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
setShowSuccess(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Close modal after save (and optional refetch) completes
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error('Error saving form:', error);
|
||||
// Don't close modal on error - let the parent handle error display
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
setIsWaitingForRefetch(false);
|
||||
setShowSuccess(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -441,7 +517,7 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
return (
|
||||
<div className="w-full">
|
||||
<Select
|
||||
value={String(value)}
|
||||
value={value}
|
||||
onChange={(newValue) => handleFieldChange(field.name, newValue)}
|
||||
options={field.options || []}
|
||||
placeholder={field.placeholder}
|
||||
@@ -586,14 +662,15 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
};
|
||||
|
||||
const StatusIcon = defaultStatusIndicator.icon;
|
||||
const isProcessing = loading || isSaving || isWaitingForRefetch;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
size={size}
|
||||
closeOnOverlayClick={!loading}
|
||||
closeOnEscape={!loading}
|
||||
closeOnOverlayClick={!isProcessing}
|
||||
closeOnEscape={!isProcessing}
|
||||
showCloseButton={false}
|
||||
>
|
||||
<ModalHeader
|
||||
@@ -601,8 +678,13 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Status indicator */}
|
||||
<div
|
||||
className="flex-shrink-0 p-2 rounded-lg"
|
||||
style={{ backgroundColor: `${defaultStatusIndicator.color}15` }}
|
||||
className={`flex-shrink-0 p-2 rounded-lg transition-all ${
|
||||
defaultStatusIndicator.isCritical ? 'ring-2 ring-offset-2' : ''
|
||||
} ${defaultStatusIndicator.isHighlight ? 'shadow-lg' : ''}`}
|
||||
style={{
|
||||
backgroundColor: `${defaultStatusIndicator.color}15`,
|
||||
...(defaultStatusIndicator.isCritical && { ringColor: defaultStatusIndicator.color })
|
||||
}}
|
||||
>
|
||||
{StatusIcon && (
|
||||
<StatusIcon
|
||||
@@ -612,25 +694,13 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Title and status */}
|
||||
<div>
|
||||
{/* Title and subtitle */}
|
||||
<div className="flex-1">
|
||||
<h2 className="text-xl font-semibold text-[var(--text-primary)]">
|
||||
{title}
|
||||
</h2>
|
||||
<div
|
||||
className="text-sm font-medium mt-1"
|
||||
style={{ color: defaultStatusIndicator.color }}
|
||||
>
|
||||
{defaultStatusIndicator.text}
|
||||
{defaultStatusIndicator.isCritical && (
|
||||
<span className="ml-2 text-xs">⚠️</span>
|
||||
)}
|
||||
{defaultStatusIndicator.isHighlight && (
|
||||
<span className="ml-2 text-xs">⭐</span>
|
||||
)}
|
||||
</div>
|
||||
{subtitle && (
|
||||
<p className="text-sm text-[var(--text-secondary)] mt-1">
|
||||
<p className="text-sm text-[var(--text-secondary)] mt-0.5">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
@@ -642,11 +712,28 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
/>
|
||||
|
||||
<ModalBody>
|
||||
{loading && (
|
||||
{(loading || isSaving || isWaitingForRefetch || showSuccess) && (
|
||||
<div className="absolute inset-0 bg-[var(--bg-primary)]/80 backdrop-blur-sm flex items-center justify-center z-10">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[var(--color-primary)]"></div>
|
||||
<span className="text-[var(--text-secondary)]">{t('common:modals.saving', 'Guardando...')}</span>
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
{!showSuccess ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[var(--color-primary)]"></div>
|
||||
<span className="text-[var(--text-secondary)]">
|
||||
{isWaitingForRefetch
|
||||
? t('common:modals.refreshing', 'Actualizando datos...')
|
||||
: isSaving
|
||||
? t('common:modals.saving', 'Guardando...')
|
||||
: t('common:modals.loading', 'Cargando...')}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-green-500 text-4xl">✓</div>
|
||||
<span className="text-[var(--text-secondary)] font-medium">
|
||||
{t('common:modals.success', 'Guardado correctamente')}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -703,7 +790,7 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCancel}
|
||||
disabled={loading}
|
||||
disabled={loading || isSaving || isWaitingForRefetch}
|
||||
className="min-w-[80px]"
|
||||
>
|
||||
{t('common:modals.actions.cancel', 'Cancelar')}
|
||||
@@ -711,10 +798,10 @@ export const AddModal: React.FC<AddModalProps> = ({
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSave}
|
||||
disabled={loading}
|
||||
disabled={loading || isSaving || isWaitingForRefetch}
|
||||
className="min-w-[80px]"
|
||||
>
|
||||
{loading ? (
|
||||
{loading || isSaving || isWaitingForRefetch ? (
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
|
||||
) : (
|
||||
t('common:modals.actions.save', 'Guardar')
|
||||
|
||||
Reference in New Issue
Block a user