fix
This commit is contained in:
parent
d347023211
commit
d9511ae7c5
@ -1,5 +1,5 @@
|
|||||||
import React, { useMemo, useCallback } from 'react';
|
import React, { useMemo, useCallback } from 'react';
|
||||||
import { useRealtime } from '../../contexts/RealtimeContext';
|
import { useCellLock } from '../../contexts/RealtimeContext';
|
||||||
|
|
||||||
// Константы вне компонента
|
// Константы вне компонента
|
||||||
const BASE_CELL_STYLES = {
|
const BASE_CELL_STYLES = {
|
||||||
@ -136,35 +136,20 @@ const createHighlightedContent = (originalValue, displayValue, searchQueries) =>
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const CellComponent = ({
|
const CellComponent = ({ cell, row, column, onClick, globalFilter, columnFilter, backgroundColor, isEditable, isInvalid, vspOptions }) => {
|
||||||
cell,
|
|
||||||
row,
|
|
||||||
column,
|
|
||||||
onClick,
|
|
||||||
globalFilter,
|
|
||||||
columnFilter,
|
|
||||||
backgroundColor,
|
|
||||||
color,
|
|
||||||
isEditable,
|
|
||||||
isUpdating,
|
|
||||||
onCellNumberClick,
|
|
||||||
isInvalid,
|
|
||||||
vspOptions,
|
|
||||||
}) => {
|
|
||||||
const { lockedCells } = useRealtime();
|
|
||||||
const cellKey = `${row.id}_${column.id}`;
|
const cellKey = `${row.id}_${column.id}`;
|
||||||
const isLocked = lockedCells.includes(cellKey);
|
const isLocked = useCellLock(cellKey);
|
||||||
|
|
||||||
const isVspDropdown = column?.columnDef?.editType === 'vsp_dropdown';
|
const isVspDropdown = column?.columnDef?.editType === 'vsp_dropdown';
|
||||||
|
|
||||||
// Мемоизация значения
|
// Мемоизация значения
|
||||||
const { rawValue, displayValue, isNumeric } = useMemo(() => {
|
const { rawValue, displayValue } = useMemo(() => {
|
||||||
const value = cell.getValue();
|
const value = cell.getValue();
|
||||||
const isNum = value !== null && value !== undefined && value !== '' && !Number.isNaN(Number(value));
|
const isNum = value !== null && value !== undefined && value !== '' && !Number.isNaN(Number(value));
|
||||||
let display = String(value || '');
|
let display = String(value || '');
|
||||||
|
|
||||||
if (isVspDropdown && value != null) {
|
if (isVspDropdown && value != null) {
|
||||||
const vsp = vspOptions?.find(v => v.id === Number(value));
|
const vsp = vspOptions?.find((v) => v.id === Number(value));
|
||||||
if (vsp) {
|
if (vsp) {
|
||||||
return { rawValue: value, displayValue: vsp.registration_number, isNumeric: false };
|
return { rawValue: value, displayValue: vsp.registration_number, isNumeric: false };
|
||||||
}
|
}
|
||||||
@ -214,7 +199,7 @@ const CellComponent = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
// biome-ignore lint/a11y/useKeyWithClickEvents: <explanation>
|
// biome-ignore lint/a11y/useKeyWithClickEvents: <explanation>
|
||||||
<div type="button" className='cell' style={cellStyles} onClick={handleClick}>
|
<div type='button' className='cell' style={cellStyles} onClick={handleClick}>
|
||||||
<span style={CONTAINER_STYLES}>{highlightedContent}</span>
|
<span style={CONTAINER_STYLES}>{highlightedContent}</span>
|
||||||
{lockBadge}
|
{lockBadge}
|
||||||
</div>
|
</div>
|
||||||
@ -232,8 +217,6 @@ const Cell = React.memo(CellComponent, (prevProps, nextProps) => {
|
|||||||
prevProps.backgroundColor === nextProps.backgroundColor &&
|
prevProps.backgroundColor === nextProps.backgroundColor &&
|
||||||
prevProps.isInvalid === nextProps.isInvalid &&
|
prevProps.isInvalid === nextProps.isInvalid &&
|
||||||
prevProps.isEditable === nextProps.isEditable &&
|
prevProps.isEditable === nextProps.isEditable &&
|
||||||
prevProps.isUpdating === nextProps.isUpdating &&
|
|
||||||
prevProps.onCellNumberClick === nextProps.onCellNumberClick &&
|
|
||||||
prevProps.vspOptions === nextProps.vspOptions
|
prevProps.vspOptions === nextProps.vspOptions
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useRealtime } from '../../contexts/RealtimeContext';
|
import { useRealtimeActions } from '../../contexts/RealtimeContext';
|
||||||
import { calculateFormula, extractFormula, formatNumber, isFormula } from '../../utils/formulaUtils';
|
import { calculateFormula, extractFormula, formatNumber, isFormula } from '../../utils/formulaUtils';
|
||||||
import { loadFromStorage, saveToStorage } from '../../utils/localStorageUtils';
|
import { loadFromStorage, saveToStorage } from '../../utils/localStorageUtils';
|
||||||
|
|
||||||
@ -30,7 +30,7 @@ const TEXTAREA_STYLES = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const EditCell = memo(({ refCell, onChange, disabled, value, tableId, cellId, table }) => {
|
const EditCell = memo(({ refCell, onChange, disabled, value, tableId, cellId, table }) => {
|
||||||
const { endEditing: contextEndEditing } = useRealtime();
|
const { endEditing: contextEndEditing } = useRealtimeActions();
|
||||||
const storageKey = `formula_${tableId}_${cellId}`;
|
const storageKey = `formula_${tableId}_${cellId}`;
|
||||||
|
|
||||||
const [state, setState] = useState(() => ({
|
const [state, setState] = useState(() => ({
|
||||||
@ -91,7 +91,7 @@ const EditCell = memo(({ refCell, onChange, disabled, value, tableId, cellId, ta
|
|||||||
const resize = () => {
|
const resize = () => {
|
||||||
el.style.minHeight = '3rem';
|
el.style.minHeight = '3rem';
|
||||||
el.style.height = '3rem';
|
el.style.height = '3rem';
|
||||||
el.style.height = el.scrollHeight + 'px';
|
el.style.height = `${el.scrollHeight}px`;
|
||||||
el.style.maxHeight = '180px';
|
el.style.maxHeight = '180px';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -1,111 +1,120 @@
|
|||||||
import React, { memo, useEffect, useRef, useLayoutEffect, useState, useCallback, useMemo } from 'react';
|
import { FormControl, MenuItem, Select } from '@mui/material';
|
||||||
import { FormControl, Select, MenuItem } from '@mui/material';
|
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { useRealtime } from '../../contexts/RealtimeContext';
|
import { useRealtimeActions, useVspOptions } from '../../contexts/RealtimeContext';
|
||||||
|
|
||||||
const EDITOR_STYLES = {
|
const EDITOR_STYLES = {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
zIndex: 12,
|
zIndex: 12,
|
||||||
top: 0,
|
top: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
const VspDropdownEditCell = memo(({ refCell, onChange, disabled, value, table }) => {
|
const VspDropdownEditCell = memo(({ refCell, onChange, disabled, value, table }) => {
|
||||||
const { endEditing: contextEndEditing, vspOptions } = useRealtime();
|
const { endEditing: contextEndEditing } = useRealtimeActions();
|
||||||
|
const vspOptions = useVspOptions();
|
||||||
|
|
||||||
const [selectedValue, setSelectedValue] = useState(() => value ?? '');
|
const [selectedValue, setSelectedValue] = useState(() => value ?? '');
|
||||||
const [position, setPosition] = useState();
|
const [position, setPosition] = useState();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
const refFinished = useRef(false);
|
const refFinished = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
}, 80);
|
}, 80);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!refCell?.current) return;
|
if (!refCell?.current) return;
|
||||||
|
|
||||||
const td = refCell.current.offsetParent;
|
const td = refCell.current.offsetParent;
|
||||||
const tr = td?.offsetParent;
|
const tr = td?.offsetParent;
|
||||||
|
|
||||||
if (td && tr) {
|
if (td && tr) {
|
||||||
setPosition({
|
setPosition({
|
||||||
left: td.offsetLeft,
|
left: td.offsetLeft,
|
||||||
width: td.offsetWidth,
|
width: td.offsetWidth,
|
||||||
translateY: tr.style.transform || '',
|
translateY: tr.style.transform || '',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [refCell]);
|
}, [refCell]);
|
||||||
|
|
||||||
const finishEditing = useCallback(() => {
|
const finishEditing = useCallback(() => {
|
||||||
if (refFinished.current) return;
|
if (refFinished.current) return;
|
||||||
refFinished.current = true;
|
refFinished.current = true;
|
||||||
table.setEditingCell(null);
|
table.setEditingCell(null);
|
||||||
const editingCell = table.getState().editingCell;
|
const editingCell = table.getState().editingCell;
|
||||||
if (editingCell) {
|
if (editingCell) {
|
||||||
contextEndEditing?.(editingCell.row, editingCell.column);
|
contextEndEditing?.(editingCell.row, editingCell.column);
|
||||||
}
|
}
|
||||||
}, [table, contextEndEditing]);
|
}, [table, contextEndEditing]);
|
||||||
|
|
||||||
const handleSelectChange = useCallback((e) => {
|
const handleSelectChange = useCallback(
|
||||||
const val = e.target.value;
|
(e) => {
|
||||||
if (val == null || val === '') return;
|
const val = e.target.value;
|
||||||
refFinished.current = true;
|
if (val == null || val === '') return;
|
||||||
setSelectedValue(val);
|
refFinished.current = true;
|
||||||
onChange?.(val);
|
setSelectedValue(val);
|
||||||
const editingCell = table.getState().editingCell;
|
onChange?.(val);
|
||||||
if (editingCell) {
|
const editingCell = table.getState().editingCell;
|
||||||
contextEndEditing?.(editingCell.row, editingCell.column);
|
if (editingCell) {
|
||||||
}
|
contextEndEditing?.(editingCell.row, editingCell.column);
|
||||||
}, [onChange, table, contextEndEditing]);
|
}
|
||||||
|
},
|
||||||
|
[onChange, table, contextEndEditing],
|
||||||
|
);
|
||||||
|
|
||||||
const handleSelectClose = useCallback((_event, reason) => {
|
const handleSelectClose = useCallback(
|
||||||
if (reason === 'selectOption') return;
|
(_event, reason) => {
|
||||||
finishEditing();
|
if (reason === 'selectOption') return;
|
||||||
}, [finishEditing]);
|
finishEditing();
|
||||||
|
},
|
||||||
|
[finishEditing],
|
||||||
|
);
|
||||||
|
|
||||||
const editorStyles = useMemo(() => ({
|
const editorStyles = useMemo(
|
||||||
...EDITOR_STYLES,
|
() => ({
|
||||||
left: position?.left || 0,
|
...EDITOR_STYLES,
|
||||||
width: position?.width || 0,
|
left: position?.left || 0,
|
||||||
transform: position?.translateY || 0,
|
width: position?.width || 0,
|
||||||
}), [position]);
|
transform: position?.translateY || 0,
|
||||||
|
}),
|
||||||
|
[position],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
{position &&
|
{position && (
|
||||||
<div style={editorStyles}>
|
<div style={editorStyles}>
|
||||||
<FormControl fullWidth size="small">
|
<FormControl fullWidth size='small'>
|
||||||
<Select
|
<Select
|
||||||
value={selectedValue}
|
value={selectedValue}
|
||||||
onChange={handleSelectChange}
|
onChange={handleSelectChange}
|
||||||
open={open}
|
open={open}
|
||||||
onClose={handleSelectClose}
|
onClose={handleSelectClose}
|
||||||
displayEmpty
|
displayEmpty
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
MenuProps={{
|
MenuProps={{
|
||||||
anchorOrigin: { vertical: 'bottom', horizontal: 'left' },
|
anchorOrigin: { vertical: 'bottom', horizontal: 'left' },
|
||||||
transformOrigin: { vertical: 'top', horizontal: 'left' },
|
transformOrigin: { vertical: 'top', horizontal: 'left' },
|
||||||
}}
|
}}>
|
||||||
>
|
<MenuItem value='' disabled>
|
||||||
<MenuItem value="" disabled>
|
Выберите ВСП
|
||||||
Выберите ВСП
|
</MenuItem>
|
||||||
</MenuItem>
|
{vspOptions.map((option) => (
|
||||||
{vspOptions.map((option) => (
|
<MenuItem key={option.id} value={option.id}>
|
||||||
<MenuItem key={option.id} value={option.id}>
|
{option.registration_number}
|
||||||
{option.registration_number}
|
</MenuItem>
|
||||||
</MenuItem>
|
))}
|
||||||
))}
|
</Select>
|
||||||
</Select>
|
</FormControl>
|
||||||
</FormControl>
|
</div>
|
||||||
</div>
|
)}
|
||||||
}
|
</td>
|
||||||
</td>
|
</tr>
|
||||||
</tr>
|
);
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
VspDropdownEditCell.displayName = 'VspDropdownEditCell';
|
VspDropdownEditCell.displayName = 'VspDropdownEditCell';
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
import { Box, Divider, IconButton, Stack } from '@mui/material';
|
import { Box, Divider, IconButton, Stack } from '@mui/material';
|
||||||
import { useEffect, useState } from 'react';
|
import { memo, useEffect, useState } from 'react';
|
||||||
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
||||||
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
||||||
import { StyledTextField } from '../../common/StyledTextField';
|
import { StyledTextField } from '../../common/StyledTextField';
|
||||||
import { Cancel } from '../../common/icons/icons';
|
import { Cancel } from '../../common/icons/icons';
|
||||||
|
|
||||||
export const CreateProgramModal = ({ isOpen, onClose, onCreate, title = '', isSaving = false, sheet }) => {
|
const CreateProgramModalComponent = ({ isOpen, onClose, onCreate, title = '', isSaving = false }) => {
|
||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -36,7 +36,7 @@ export const CreateProgramModal = ({ isOpen, onClose, onCreate, title = '', isSa
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
||||||
<ModalContainer height={'max-content'}>
|
<ModalContainer height='max-content'>
|
||||||
<HeaderContainer>
|
<HeaderContainer>
|
||||||
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
||||||
<ModalTitle>{title}</ModalTitle>
|
<ModalTitle>{title}</ModalTitle>
|
||||||
@ -50,7 +50,7 @@ export const CreateProgramModal = ({ isOpen, onClose, onCreate, title = '', isSa
|
|||||||
<Divider sx={{ marginBottom: '0.75rem' }} />
|
<Divider sx={{ marginBottom: '0.75rem' }} />
|
||||||
|
|
||||||
{/* <Input */}
|
{/* <Input */}
|
||||||
<StyledTextField label={'Название программы'} onChange={(e) => setName(e.target.value)}></StyledTextField>
|
<StyledTextField label='Название программы' onChange={(e) => setName(e.target.value)} />
|
||||||
<Stack
|
<Stack
|
||||||
direction='row'
|
direction='row'
|
||||||
spacing={0.75}
|
spacing={0.75}
|
||||||
@ -72,3 +72,5 @@ export const CreateProgramModal = ({ isOpen, onClose, onCreate, title = '', isSa
|
|||||||
</ModalBackdrop>
|
</ModalBackdrop>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const CreateProgramModal = memo(CreateProgramModalComponent);
|
||||||
|
|||||||
@ -1,17 +1,17 @@
|
|||||||
import { Autocomplete, Box, Divider, FormControl, IconButton, Stack, TextField } from '@mui/material';
|
import { Autocomplete, Box, Divider, FormControl, IconButton, Stack, TextField } from '@mui/material';
|
||||||
import { useEffect, useState } from 'react';
|
import { memo, useEffect, useState } from 'react';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { ExpenseItemApi } from '../../../api/expense-item';
|
import { ExpenseItemApi } from '../../../api/expense-item';
|
||||||
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
||||||
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
||||||
import { Cancel } from '../../common/icons/icons';
|
import { Cancel } from '../../common/icons/icons';
|
||||||
|
|
||||||
export const SelectExpenseItemModal = ({ isOpen, onClose, onSelect, formId, title = '', isSaving = false, sheet }) => {
|
const SelectExpenseItemModalComponent = ({ isOpen, onClose, onSelect, formId, title = '', isSaving = false, sheet }) => {
|
||||||
const [selectedValue, setSelectedValue] = useState('');
|
const [selectedValue, setSelectedValue] = useState('');
|
||||||
const [expenseItemOptions, setExpenseItemOption] = useState([]);
|
const [expenseItemOptions, setExpenseItemOption] = useState([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (formId === null) return;
|
if (!isOpen || formId == null) return;
|
||||||
ExpenseItemApi.getAll({ r_start: true, sheet: sheet }).then((data) => {
|
ExpenseItemApi.getAll({ r_start: true, sheet: sheet }).then((data) => {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setExpenseItemOption(data.result);
|
setExpenseItemOption(data.result);
|
||||||
@ -19,7 +19,7 @@ export const SelectExpenseItemModal = ({ isOpen, onClose, onSelect, formId, titl
|
|||||||
}
|
}
|
||||||
toast.error('Ошибка получения статья расходов');
|
toast.error('Ошибка получения статья расходов');
|
||||||
});
|
});
|
||||||
}, [formId]);
|
}, [formId, isOpen, sheet]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) {
|
if (!isOpen) {
|
||||||
@ -49,7 +49,7 @@ export const SelectExpenseItemModal = ({ isOpen, onClose, onSelect, formId, titl
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
||||||
<ModalContainer height={'max-content'}>
|
<ModalContainer height='max-content'>
|
||||||
<HeaderContainer>
|
<HeaderContainer>
|
||||||
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
||||||
<ModalTitle>{title}</ModalTitle>
|
<ModalTitle>{title}</ModalTitle>
|
||||||
@ -72,7 +72,7 @@ export const SelectExpenseItemModal = ({ isOpen, onClose, onSelect, formId, titl
|
|||||||
getOptionLabel={(option) => option.name || ''}
|
getOptionLabel={(option) => option.name || ''}
|
||||||
getOptionKey={(option) => option.id}
|
getOptionKey={(option) => option.id}
|
||||||
value={selectedValue}
|
value={selectedValue}
|
||||||
onChange={(event, newValue) => {
|
onChange={(_event, newValue) => {
|
||||||
setSelectedValue(newValue);
|
setSelectedValue(newValue);
|
||||||
}}
|
}}
|
||||||
slotProps={{
|
slotProps={{
|
||||||
@ -118,3 +118,5 @@ export const SelectExpenseItemModal = ({ isOpen, onClose, onSelect, formId, titl
|
|||||||
</ModalBackdrop>
|
</ModalBackdrop>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const SelectExpenseItemModal = memo(SelectExpenseItemModalComponent);
|
||||||
|
|||||||
@ -1,17 +1,17 @@
|
|||||||
import { Box, Divider, FormControl, IconButton, MenuItem, Select, Stack } from '@mui/material';
|
import { Box, Divider, FormControl, IconButton, MenuItem, Select, Stack } from '@mui/material';
|
||||||
import { useEffect, useState } from 'react';
|
import { memo, useEffect, useState } from 'react';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { DictVspApi } from '../../../api/dict-vsp';
|
import { DictVspApi } from '../../../api/dict-vsp';
|
||||||
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
import { DangerOutlinedButton, PrimaryButton } from '../../common/Buttons/Buttons';
|
||||||
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
import { HeaderContainer, ModalBackdrop, ModalContainer, ModalTitle } from '../../common/Modal/ModalStyled';
|
||||||
import { Cancel } from '../../common/icons/icons';
|
import { Cancel } from '../../common/icons/icons';
|
||||||
|
|
||||||
export const SelectVspModal = ({ isOpen, onClose, onSelect, formId, title = 'Выбор ВСП', isSaving = false }) => {
|
const SelectVspModalComponent = ({ isOpen, onClose, onSelect, formId, title = 'Выбор ВСП', isSaving = false }) => {
|
||||||
const [selectedValue, setSelectedValue] = useState('');
|
const [selectedValue, setSelectedValue] = useState('');
|
||||||
const [vspOptions, setVspOption] = useState([]);
|
const [vspOptions, setVspOption] = useState([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (formId === null) return;
|
if (!isOpen || formId == null) return;
|
||||||
DictVspApi.getDropdownVsp({ form_id: formId }).then((data) => {
|
DictVspApi.getDropdownVsp({ form_id: formId }).then((data) => {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setVspOption(data.result);
|
setVspOption(data.result);
|
||||||
@ -19,7 +19,7 @@ export const SelectVspModal = ({ isOpen, onClose, onSelect, formId, title = 'В
|
|||||||
}
|
}
|
||||||
toast.error('Ошибка получения ВСП');
|
toast.error('Ошибка получения ВСП');
|
||||||
});
|
});
|
||||||
}, [formId]);
|
}, [formId, isOpen]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) {
|
if (!isOpen) {
|
||||||
@ -49,7 +49,7 @@ export const SelectVspModal = ({ isOpen, onClose, onSelect, formId, title = 'В
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
<ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
|
||||||
<ModalContainer height={'max-content'}>
|
<ModalContainer height='max-content'>
|
||||||
<HeaderContainer>
|
<HeaderContainer>
|
||||||
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
<Stack direction='row' spacing={2} sx={{ alignItems: 'center' }}>
|
||||||
<ModalTitle>{title}</ModalTitle>
|
<ModalTitle>{title}</ModalTitle>
|
||||||
@ -99,3 +99,5 @@ export const SelectVspModal = ({ isOpen, onClose, onSelect, formId, title = 'В
|
|||||||
</ModalBackdrop>
|
</ModalBackdrop>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const SelectVspModal = memo(SelectVspModalComponent);
|
||||||
|
|||||||
@ -1,40 +1,32 @@
|
|||||||
|
import { MaterialReactTable, useMaterialReactTable } from 'material-react-table';
|
||||||
import React, { useState, useMemo, useRef, useEffect, useCallback, useTransition } from 'react';
|
import React, { useState, useMemo, useRef, useEffect, useCallback, useTransition } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import {
|
|
||||||
useMaterialReactTable,
|
|
||||||
MaterialReactTable,
|
|
||||||
} from 'material-react-table';
|
|
||||||
|
|
||||||
import useRealtimeData from './hooks/useRealtimeData';
|
|
||||||
import { getTableColumns } from './tableColumns';
|
|
||||||
import { Cell, EditCell } from './index';
|
|
||||||
import { TableHead } from './TableHead/TableHead';
|
|
||||||
import SettingsPanel from './SettingPanel/SettingPanel';
|
|
||||||
import { ColumnSelectionOverlay } from './ColumnSelectionOverlay/ColumnSelectionOverlay';
|
import { ColumnSelectionOverlay } from './ColumnSelectionOverlay/ColumnSelectionOverlay';
|
||||||
|
import SettingsPanel from './SettingPanel/SettingPanel';
|
||||||
|
import { TableHead } from './TableHead/TableHead';
|
||||||
|
import useRealtimeData from './hooks/useRealtimeData';
|
||||||
|
import { Cell, EditCell } from './index';
|
||||||
|
import { getTableColumns } from './tableColumns';
|
||||||
|
|
||||||
import { useColumnSettings } from './hooks/useColumnSettings';
|
|
||||||
import { useTableScale } from './hooks/useTableScale';
|
|
||||||
import { useHeaderPortal } from './hooks/useHeaderPortal';
|
|
||||||
import { useValidationRules } from './hooks/useValidationRules';
|
|
||||||
import {
|
|
||||||
BASE_TABLE_CONFIG,
|
|
||||||
getTableBodyCellProps,
|
|
||||||
getTablePaperStyles,
|
|
||||||
TABLE_ROW_HEIGHT,
|
|
||||||
} from './constants/tableConfig';
|
|
||||||
import { useRealtime } from './contexts/RealtimeContext';
|
|
||||||
import { toast } from 'react-toastify';
|
|
||||||
import { CircularProgress } from '@mui/material';
|
import { CircularProgress } from '@mui/material';
|
||||||
import { additionExpenseRowTable, additionVspRowTable } from './constants/addingRowConfig';
|
|
||||||
import { SelectVspModal } from './Modals/SelectVspModal';
|
|
||||||
import { SelectExpenseItemModal } from './Modals/SelectExpenseItemModal';
|
|
||||||
import { getRowId } from './utils/rowUtils';
|
|
||||||
import { debounce } from '@mui/material';
|
import { debounce } from '@mui/material';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
import { CreateProgramModal } from './Modals/CreateProgramProjectModal';
|
import { CreateProgramModal } from './Modals/CreateProgramProjectModal';
|
||||||
|
import { SelectExpenseItemModal } from './Modals/SelectExpenseItemModal';
|
||||||
|
import { SelectVspModal } from './Modals/SelectVspModal';
|
||||||
|
import { additionExpenseRowTable, additionVspRowTable } from './constants/addingRowConfig';
|
||||||
|
import { BASE_TABLE_CONFIG, TABLE_ROW_HEIGHT, getTableBodyCellProps, getTablePaperStyles } from './constants/tableConfig';
|
||||||
|
import { useRealtimeActions } from './contexts/RealtimeContext';
|
||||||
|
import { useColumnSettings } from './hooks/useColumnSettings';
|
||||||
|
import { useHeaderPortal } from './hooks/useHeaderPortal';
|
||||||
|
import { useTableScale } from './hooks/useTableScale';
|
||||||
|
import { useValidationRules } from './hooks/useValidationRules';
|
||||||
|
import { getRowId } from './utils/rowUtils';
|
||||||
|
|
||||||
import { FormsNoCanAddRow } from './constants/formConfig';
|
|
||||||
import { DictVspApi } from '../../api/dict-vsp';
|
import { DictVspApi } from '../../api/dict-vsp';
|
||||||
import { useAuth } from '../../app/context/AuthProvider';
|
import { useAuth } from '../../app/context/AuthProvider';
|
||||||
|
import { FormsNoCanAddRow } from './constants/formConfig';
|
||||||
|
|
||||||
const CONFIG_CACHE = new Map();
|
const CONFIG_CACHE = new Map();
|
||||||
|
|
||||||
@ -65,11 +57,7 @@ const getColumnVirtualizerOptions = ({ table }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const hasVspDropdown = (columns) =>
|
const hasVspDropdown = (columns) =>
|
||||||
columns.some(
|
columns.some((column) => column.editType === 'vsp_dropdown' || (column.columns?.length && hasVspDropdown(column.columns)));
|
||||||
(column) =>
|
|
||||||
column.editType === 'vsp_dropdown' ||
|
|
||||||
(column.columns?.length && hasVspDropdown(column.columns)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const tableContentStyle = {
|
const tableContentStyle = {
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
@ -91,7 +79,13 @@ const loadingOverlayStyle = {
|
|||||||
|
|
||||||
const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const { data, columnsCurStage, isLoading: isTableLoading, editingCells: dataEditingCells } = useRealtimeData(formId, sheetName, direction, formType, year);
|
const userRoleId = user?.role_id;
|
||||||
|
const {
|
||||||
|
data,
|
||||||
|
columnsCurStage,
|
||||||
|
isLoading: isTableLoading,
|
||||||
|
editingCells: dataEditingCells,
|
||||||
|
} = useRealtimeData(formId, sheetName, direction, formType, year);
|
||||||
const [globalFilter, setGlobalFilter] = useState('');
|
const [globalFilter, setGlobalFilter] = useState('');
|
||||||
const [showColumnFilters, setShowColumnFilters] = useState(false);
|
const [showColumnFilters, setShowColumnFilters] = useState(false);
|
||||||
const [selectedColumnId, setSelectedColumnId] = useState();
|
const [selectedColumnId, setSelectedColumnId] = useState();
|
||||||
@ -101,12 +95,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
const [, startTransition] = useTransition();
|
const [, startTransition] = useTransition();
|
||||||
const [editingCell, setEditingCell] = useState(null);
|
const [editingCell, setEditingCell] = useState(null);
|
||||||
const [columnsConfig, setColumnsConfig] = useState(null);
|
const [columnsConfig, setColumnsConfig] = useState(null);
|
||||||
const { errors: validationErrors, isCellInvalid } = useValidationRules(
|
const { errors: validationErrors, isCellInvalid } = useValidationRules(data, columnsConfig?.columns, formType, sheetName);
|
||||||
data,
|
|
||||||
columnsConfig?.columns,
|
|
||||||
formType,
|
|
||||||
sheetName,
|
|
||||||
);
|
|
||||||
|
|
||||||
const [expanded, setExpanded] = useState(true);
|
const [expanded, setExpanded] = useState(true);
|
||||||
const [showOnlyDepth2, setShowOnlyDepth2] = useState(false);
|
const [showOnlyDepth2, setShowOnlyDepth2] = useState(false);
|
||||||
@ -115,10 +104,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
const [isOpenModalSelectExpenseItem, setIsOpenModalSelectExpenseItem] = useState(false);
|
const [isOpenModalSelectExpenseItem, setIsOpenModalSelectExpenseItem] = useState(false);
|
||||||
const [createModalType, setCreateModalType] = useState(null);
|
const [createModalType, setCreateModalType] = useState(null);
|
||||||
|
|
||||||
const isFormNoCanAddRow = useMemo(
|
const isFormNoCanAddRow = useMemo(() => FormsNoCanAddRow[formType]?.includes(sheetName) ?? false, [formType, sheetName]);
|
||||||
() => FormsNoCanAddRow[formType]?.includes(sheetName) ?? false,
|
|
||||||
[formType, sheetName],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isVspAdditionRow = useMemo(() => {
|
const isVspAdditionRow = useMemo(() => {
|
||||||
if (!formType || !sheetName) return false;
|
if (!formType || !sheetName) return false;
|
||||||
@ -133,11 +119,12 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
}, [formType, sheetName]);
|
}, [formType, sheetName]);
|
||||||
|
|
||||||
const handleGlobalFilterChange = useMemo(
|
const handleGlobalFilterChange = useMemo(
|
||||||
() => debounce((value) => {
|
() =>
|
||||||
startTransition(() => {
|
debounce((value) => {
|
||||||
setGlobalFilter(value);
|
startTransition(() => {
|
||||||
});
|
setGlobalFilter(value);
|
||||||
}, 300),
|
});
|
||||||
|
}, 300),
|
||||||
[startTransition],
|
[startTransition],
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -151,7 +138,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
addProgram: contextAddProgram,
|
addProgram: contextAddProgram,
|
||||||
addProject: contextAddProject,
|
addProject: contextAddProject,
|
||||||
setVspOptions,
|
setVspOptions,
|
||||||
} = useRealtime();
|
} = useRealtimeActions();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
columnSizing,
|
columnSizing,
|
||||||
@ -170,8 +157,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
const rowVirtualizerRef = useRef(null);
|
const rowVirtualizerRef = useRef(null);
|
||||||
const columnVirtualizerRef = useRef(null);
|
const columnVirtualizerRef = useRef(null);
|
||||||
|
|
||||||
const { sizeMult, setSizeMult, tableScaleStyle, tableWrapperStyle } =
|
const { sizeMult, setSizeMult, tableScaleStyle, tableWrapperStyle } = useTableScale();
|
||||||
useTableScale();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
rowVirtualizerRef.current?.measure?.();
|
rowVirtualizerRef.current?.measure?.();
|
||||||
@ -180,6 +166,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!formType || !sheetName) return;
|
if (!formType || !sheetName) return;
|
||||||
|
let isCancelled = false;
|
||||||
const cacheKey = `${formType}_${sheetName}`;
|
const cacheKey = `${formType}_${sheetName}`;
|
||||||
|
|
||||||
if (CONFIG_CACHE.has(cacheKey)) {
|
if (CONFIG_CACHE.has(cacheKey)) {
|
||||||
@ -191,38 +178,48 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
try {
|
try {
|
||||||
const { config } = await import(`./constants/${formType}/${sheetName}.js`);
|
const { config } = await import(`./constants/${formType}/${sheetName}.js`);
|
||||||
CONFIG_CACHE.set(cacheKey, config.config);
|
CONFIG_CACHE.set(cacheKey, config.config);
|
||||||
setColumnsConfig(config.config);
|
if (!isCancelled) setColumnsConfig(config.config);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Failed to load config for ${formType}/${sheetName}:`, error);
|
console.error(`Failed to load config for ${formType}/${sheetName}:`, error);
|
||||||
setColumnsConfig({ columns: [], colors: {} });
|
if (!isCancelled) setColumnsConfig({ columns: [], colors: {} });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadConfig();
|
loadConfig();
|
||||||
|
return () => {
|
||||||
|
isCancelled = true;
|
||||||
|
};
|
||||||
}, [formType, sheetName]);
|
}, [formType, sheetName]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!formId || !columnsConfig?.columns) return;
|
if (!formId || !columnsConfig?.columns) return;
|
||||||
|
|
||||||
if (!hasVspDropdown(columnsConfig.columns)) return;
|
if (!hasVspDropdown(columnsConfig.columns)) return;
|
||||||
|
let isCancelled = false;
|
||||||
|
|
||||||
DictVspApi.getDropdownVsp({ form_id: formId }).then(data => {
|
DictVspApi.getDropdownVsp({ form_id: formId }).then((data) => {
|
||||||
if (data.success) {
|
if (!isCancelled && data.success) {
|
||||||
setVspOptions(data.result);
|
setVspOptions(data.result);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isCancelled = true;
|
||||||
|
};
|
||||||
}, [formId, columnsConfig, setVspOptions]);
|
}, [formId, columnsConfig, setVspOptions]);
|
||||||
|
|
||||||
|
const handleUpdateCell = useCallback(
|
||||||
const handleUpdateCell = useCallback(async (row, column, value) => {
|
(row, column, value) => {
|
||||||
return await contextUpdateCell(row, column, value);
|
return contextUpdateCell(row, column, value);
|
||||||
}, [contextUpdateCell]);
|
},
|
||||||
|
[contextUpdateCell],
|
||||||
|
);
|
||||||
|
|
||||||
const handleClickRowCell = useCallback((rowId) => {
|
const handleClickRowCell = useCallback((rowId) => {
|
||||||
setRowSelection((prev) => ({
|
setRowSelection((prev) => ({
|
||||||
[rowId]: !prev[rowId],
|
[rowId]: !prev[rowId],
|
||||||
}));
|
}));
|
||||||
}, [])
|
}, []);
|
||||||
|
|
||||||
const handleColumnSelect = useCallback((columnId) => {
|
const handleColumnSelect = useCallback((columnId) => {
|
||||||
setSelectedColumnId((prev) => {
|
setSelectedColumnId((prev) => {
|
||||||
@ -259,8 +256,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
EditCell,
|
EditCell,
|
||||||
columnsConfig,
|
columnsConfig,
|
||||||
columnsCurStage,
|
columnsCurStage,
|
||||||
user,
|
userRoleId,
|
||||||
onCellUpdate: handleUpdateCell,
|
|
||||||
onCellNumberClick: handleClickRowCell,
|
onCellNumberClick: handleClickRowCell,
|
||||||
onCellUpdateError: handleCellUpdateError,
|
onCellUpdateError: handleCellUpdateError,
|
||||||
isCellInvalid,
|
isCellInvalid,
|
||||||
@ -269,15 +265,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
console.error('Error creating columns:', error);
|
console.error('Error creating columns:', error);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}, [
|
}, [columnsConfig, columnsCurStage, userRoleId, handleCellUpdateError, handleClickRowCell, handleUpdateCell, isCellInvalid]);
|
||||||
columnsConfig,
|
|
||||||
columnsCurStage,
|
|
||||||
user,
|
|
||||||
handleCellUpdateError,
|
|
||||||
handleClickRowCell,
|
|
||||||
handleUpdateCell,
|
|
||||||
isCellInvalid,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// MRT запоминает индексы pinned-колонок до завершения асинхронной
|
// MRT запоминает индексы pinned-колонок до завершения асинхронной
|
||||||
// загрузки конфигурации. Новая ссылка на columnPinning заставляет
|
// загрузки конфигурации. Новая ссылка на columnPinning заставляет
|
||||||
@ -304,10 +292,13 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
const selectedColumnIdRef = useRef(selectedColumnId);
|
const selectedColumnIdRef = useRef(selectedColumnId);
|
||||||
selectedColumnIdRef.current = selectedColumnId;
|
selectedColumnIdRef.current = selectedColumnId;
|
||||||
|
|
||||||
const tableMeta = useMemo(() => ({
|
const tableMeta = useMemo(
|
||||||
updateCell: handleUpdateCell,
|
() => ({
|
||||||
getSelectedColumnId: () => selectedColumnIdRef.current,
|
updateCell: handleUpdateCell,
|
||||||
}), [handleUpdateCell]);
|
getSelectedColumnId: () => selectedColumnIdRef.current,
|
||||||
|
}),
|
||||||
|
[handleUpdateCell],
|
||||||
|
);
|
||||||
|
|
||||||
const createTableConfig = ({
|
const createTableConfig = ({
|
||||||
columns,
|
columns,
|
||||||
@ -355,7 +346,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
showColumnFilters,
|
showColumnFilters,
|
||||||
rowSelection,
|
rowSelection,
|
||||||
editingCell,
|
editingCell,
|
||||||
expanded
|
expanded,
|
||||||
},
|
},
|
||||||
initialState: {
|
initialState: {
|
||||||
expanded: true,
|
expanded: true,
|
||||||
@ -377,7 +368,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
minHeight: '1px',
|
minHeight: '1px',
|
||||||
maxHeight: '1px',
|
maxHeight: '1px',
|
||||||
visibility: 'hidden',
|
visibility: 'hidden',
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
muiTablePaperProps: getTablePaperStyles(),
|
muiTablePaperProps: getTablePaperStyles(),
|
||||||
@ -396,69 +387,74 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const tableConfig = useMemo(() => createTableConfig({
|
const tableConfig = useMemo(
|
||||||
columns,
|
() =>
|
||||||
data,
|
createTableConfig({
|
||||||
columnSizing,
|
columns,
|
||||||
columnPinning,
|
data,
|
||||||
columnVisibility,
|
columnSizing,
|
||||||
expanded,
|
columnPinning,
|
||||||
globalFilter,
|
columnVisibility,
|
||||||
showColumnFilters,
|
expanded,
|
||||||
rowSelection,
|
globalFilter,
|
||||||
containerRef,
|
showColumnFilters,
|
||||||
tableMeta,
|
rowSelection,
|
||||||
setColumnSizing,
|
containerRef,
|
||||||
setColumnPinning,
|
tableMeta,
|
||||||
setExpanded,
|
setColumnSizing,
|
||||||
editingCell,
|
setColumnPinning,
|
||||||
contextStartEditing,
|
setExpanded,
|
||||||
}), [
|
editingCell,
|
||||||
columns,
|
contextStartEditing,
|
||||||
data,
|
}),
|
||||||
columnSizing,
|
[
|
||||||
columnPinning,
|
columns,
|
||||||
columnVisibility,
|
data,
|
||||||
globalFilter,
|
columnSizing,
|
||||||
showColumnFilters,
|
columnPinning,
|
||||||
rowSelection,
|
columnVisibility,
|
||||||
containerRef,
|
globalFilter,
|
||||||
tableMeta,
|
showColumnFilters,
|
||||||
setColumnSizing,
|
rowSelection,
|
||||||
setColumnPinning,
|
containerRef,
|
||||||
editingCell,
|
tableMeta,
|
||||||
expanded,
|
setColumnSizing,
|
||||||
]);
|
setColumnPinning,
|
||||||
|
editingCell,
|
||||||
|
expanded,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const table = useMaterialReactTable(tableConfig);
|
const table = useMaterialReactTable(tableConfig);
|
||||||
const isLoadingData = columns.length > 0;
|
const isLoadingData = columns.length > 0;
|
||||||
|
|
||||||
const handleNavigateToColumn = useCallback((columnId) => {
|
const handleNavigateToColumn = useCallback(
|
||||||
if (!columnId) return;
|
(columnId) => {
|
||||||
|
if (!columnId) return;
|
||||||
|
|
||||||
setSelectedColumnId(columnId);
|
setSelectedColumnId(columnId);
|
||||||
|
|
||||||
const container = containerRef.current;
|
const container = containerRef.current;
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
||||||
const pinnedIds = new Set(columnPinning?.left || []);
|
const pinnedIds = new Set(columnPinning?.left || []);
|
||||||
if (pinnedIds.has(columnId)) return;
|
if (pinnedIds.has(columnId)) return;
|
||||||
|
|
||||||
const centerColumns = table
|
const centerColumns = table.getVisibleLeafColumns().filter((column) => !pinnedIds.has(column.id));
|
||||||
.getVisibleLeafColumns()
|
|
||||||
.filter((column) => !pinnedIds.has(column.id));
|
|
||||||
|
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
for (const column of centerColumns) {
|
for (const column of centerColumns) {
|
||||||
if (column.id === columnId) break;
|
if (column.id === columnId) break;
|
||||||
offset += column.getSize();
|
offset += column.getSize();
|
||||||
}
|
}
|
||||||
|
|
||||||
container.scrollTo({
|
container.scrollTo({
|
||||||
left: Math.max(0, offset - 40),
|
left: Math.max(0, offset - 40),
|
||||||
behavior: 'smooth',
|
behavior: 'smooth',
|
||||||
});
|
});
|
||||||
}, [columnPinning, containerRef, table]);
|
},
|
||||||
|
[columnPinning, containerRef, table],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!dataEditingCells?.line_id) {
|
if (!dataEditingCells?.line_id) {
|
||||||
@ -470,9 +466,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
const animationFrameId = requestAnimationFrame(() => {
|
const animationFrameId = requestAnimationFrame(() => {
|
||||||
try {
|
try {
|
||||||
const row = table.getRow(dataEditingCells.line_id);
|
const row = table.getRow(dataEditingCells.line_id);
|
||||||
const cell = row?.getVisibleCells().find(
|
const cell = row?.getVisibleCells().find((c) => c.column.id === dataEditingCells.column);
|
||||||
c => c.column.id === dataEditingCells.column
|
|
||||||
);
|
|
||||||
if (cell) setEditingCell(cell);
|
if (cell) setEditingCell(cell);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@ -482,10 +476,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
return () => cancelAnimationFrame(animationFrameId);
|
return () => cancelAnimationFrame(animationFrameId);
|
||||||
}, [dataEditingCells, editingCell, table]);
|
}, [dataEditingCells, editingCell, table]);
|
||||||
|
|
||||||
const getSelectedRow = useCallback(
|
const getSelectedRow = useCallback(() => table.getRowModel().rows.find((row) => rowSelectionRef.current[row.id]), [table]);
|
||||||
() => table.getRowModel().rows.find((row) => rowSelectionRef.current[row.id]),
|
|
||||||
[table],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleAddRow = useCallback(() => {
|
const handleAddRow = useCallback(() => {
|
||||||
const row = getSelectedRow();
|
const row = getSelectedRow();
|
||||||
@ -496,25 +487,37 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
contextAddRow({ expense_item_id: row.original.data.header.expense_item_id });
|
contextAddRow({ expense_item_id: row.original.data.header.expense_item_id });
|
||||||
}, [contextAddRow, getSelectedRow]);
|
}, [contextAddRow, getSelectedRow]);
|
||||||
|
|
||||||
const handleAddVspRow = useCallback((vsp_id) => {
|
const handleAddVspRow = useCallback(
|
||||||
contextAddRow({ vsp_id });
|
(vsp_id) => {
|
||||||
}, [contextAddRow]);
|
contextAddRow({ vsp_id });
|
||||||
|
},
|
||||||
|
[contextAddRow],
|
||||||
|
);
|
||||||
|
|
||||||
const handleAddExpenseItemRow = useCallback((expense_item) => {
|
const handleAddExpenseItemRow = useCallback(
|
||||||
const row = getSelectedRow();
|
(expense_item) => {
|
||||||
if (!row) return;
|
const row = getSelectedRow();
|
||||||
contextAddRow({ expense_item_id: expense_item.id, project_id: row.original.data.header.project_id });
|
if (!row) return;
|
||||||
}, [contextAddRow, getSelectedRow]);
|
contextAddRow({ expense_item_id: expense_item.id, project_id: row.original.data.header.project_id });
|
||||||
|
},
|
||||||
|
[contextAddRow, getSelectedRow],
|
||||||
|
);
|
||||||
|
|
||||||
const handleAddProgramRow = useCallback((name) => {
|
const handleAddProgramRow = useCallback(
|
||||||
contextAddProgram({ name });
|
(name) => {
|
||||||
}, [contextAddProgram]);
|
contextAddProgram({ name });
|
||||||
|
},
|
||||||
|
[contextAddProgram],
|
||||||
|
);
|
||||||
|
|
||||||
const handleAddProjectRow = useCallback((name) => {
|
const handleAddProjectRow = useCallback(
|
||||||
const row = getSelectedRow();
|
(name) => {
|
||||||
if (!row) return;
|
const row = getSelectedRow();
|
||||||
contextAddProject({ name, program_id: row.original.data.header.program_id });
|
if (!row) return;
|
||||||
}, [contextAddProject, getSelectedRow]);
|
contextAddProject({ name, program_id: row.original.data.header.program_id });
|
||||||
|
},
|
||||||
|
[contextAddProject, getSelectedRow],
|
||||||
|
);
|
||||||
|
|
||||||
const handleOpenModalSelectVsp = useCallback(() => {
|
const handleOpenModalSelectVsp = useCallback(() => {
|
||||||
setIsOpenModalSelectVsp(true);
|
setIsOpenModalSelectVsp(true);
|
||||||
@ -582,7 +585,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleToggleDepthVisibility = useCallback(() => {
|
const handleToggleDepthVisibility = useCallback(() => {
|
||||||
setShowOnlyDepth2(prev => {
|
setShowOnlyDepth2((prev) => {
|
||||||
const newState = !prev;
|
const newState = !prev;
|
||||||
|
|
||||||
if (newState) {
|
if (newState) {
|
||||||
@ -609,13 +612,13 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SettingsPanel
|
<SettingsPanel
|
||||||
selectedColumnId={selectedColumnId}
|
selectedColumnId={selectedColumnId}
|
||||||
columnPinning={columnPinning}
|
columnPinning={columnPinning}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
onPinColumn={handlePinColumn}
|
onPinColumn={handlePinColumn}
|
||||||
onUnpinColumn={handleUnpinColumn}
|
onUnpinColumn={handleUnpinColumn}
|
||||||
onToggleColumnVisibility={handleToggleColumnVisibility}
|
onToggleColumnVisibility={handleToggleColumnVisibility}
|
||||||
onSetColumnsVisibility={handleSetColumnsVisibility}
|
onSetColumnsVisibility={handleSetColumnsVisibility}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
columnsCurStage={columnsCurStage}
|
columnsCurStage={columnsCurStage}
|
||||||
onChangeSizeMult={setSizeMult}
|
onChangeSizeMult={setSizeMult}
|
||||||
@ -667,6 +670,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
columnPinning={columnPinning}
|
columnPinning={columnPinning}
|
||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
columnVisibility={columnVisibility}
|
columnVisibility={columnVisibility}
|
||||||
|
columnFilters={table.getState().columnFilters}
|
||||||
showColumnFilters={showColumnFilters}
|
showColumnFilters={showColumnFilters}
|
||||||
selectedColumnId={selectedColumnId}
|
selectedColumnId={selectedColumnId}
|
||||||
onColumnSelect={handleColumnSelect}
|
onColumnSelect={handleColumnSelect}
|
||||||
@ -683,14 +687,14 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
|
|||||||
onClose={closeSelectVspModal}
|
onClose={closeSelectVspModal}
|
||||||
formId={formId}
|
formId={formId}
|
||||||
onSelect={handleAddVspRow}
|
onSelect={handleAddVspRow}
|
||||||
title="Выбор ВСП"
|
title='Выбор ВСП'
|
||||||
/>
|
/>
|
||||||
<SelectExpenseItemModal
|
<SelectExpenseItemModal
|
||||||
isOpen={isOpenModalSelectExpenseItem}
|
isOpen={isOpenModalSelectExpenseItem}
|
||||||
onClose={closeSelectExpenseItemModal}
|
onClose={closeSelectExpenseItemModal}
|
||||||
formId={formId}
|
formId={formId}
|
||||||
onSelect={handleAddExpenseItemRow}
|
onSelect={handleAddExpenseItemRow}
|
||||||
title="Добавление строки"
|
title='Добавление строки'
|
||||||
sheet={sheetName}
|
sheet={sheetName}
|
||||||
/>
|
/>
|
||||||
<CreateProgramModal
|
<CreateProgramModal
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import { Divider, IconButton, Stack, Tooltip } from '@mui/material';
|
|||||||
import { memo, useCallback, useMemo, useState } from 'react';
|
import { memo, useCallback, useMemo, useState } from 'react';
|
||||||
import { FORM_TYPE_OPTIONS } from '../../../constants/constants';
|
import { FORM_TYPE_OPTIONS } from '../../../constants/constants';
|
||||||
import { exportSheet, exportSheetProject } from '../../../utils/exportFile';
|
import { exportSheet, exportSheetProject } from '../../../utils/exportFile';
|
||||||
|
import { stageColumnsHiddenFromPicker } from '../../Stages/constants';
|
||||||
import { ExportDefaultButton } from '../../common/Buttons/ButtonsActions';
|
import { ExportDefaultButton } from '../../common/Buttons/ButtonsActions';
|
||||||
import CollapsibleTree from '../../common/CollapsibleTree';
|
import CollapsibleTree from '../../common/CollapsibleTree';
|
||||||
import SearchComponent from '../../common/SearchComponent';
|
import SearchComponent from '../../common/SearchComponent';
|
||||||
@ -19,12 +20,11 @@ import {
|
|||||||
Search,
|
Search,
|
||||||
VisibleExpenseItems,
|
VisibleExpenseItems,
|
||||||
} from '../../common/icons/icons';
|
} from '../../common/icons/icons';
|
||||||
|
import { collectLeafColumns } from '../utils/columnUtils';
|
||||||
import { GroupByObject } from './GroupByObject/GroupByObject';
|
import { GroupByObject } from './GroupByObject/GroupByObject';
|
||||||
import { Panel } from './SettingPanel.style';
|
import { Panel } from './SettingPanel.style';
|
||||||
import ValidationErrorsAlert from './ValidationErrorsAlert';
|
import ValidationErrorsAlert from './ValidationErrorsAlert';
|
||||||
import ZoomSlider from './ZoomSlider';
|
import ZoomSlider from './ZoomSlider';
|
||||||
import { collectLeafColumns } from '../utils/columnUtils';
|
|
||||||
import { stageColumnsHiddenFromPicker } from '../../Stages/constants';
|
|
||||||
|
|
||||||
const controlSx = {
|
const controlSx = {
|
||||||
minHeight: '2.5rem',
|
minHeight: '2.5rem',
|
||||||
@ -69,13 +69,7 @@ const SettingPanel = ({
|
|||||||
() => Boolean(selectedColumnId && columnPinning?.left?.includes(selectedColumnId)),
|
() => Boolean(selectedColumnId && columnPinning?.left?.includes(selectedColumnId)),
|
||||||
[columnPinning, selectedColumnId],
|
[columnPinning, selectedColumnId],
|
||||||
);
|
);
|
||||||
const selectedColumnIds = useMemo(
|
const selectedColumnIds = useMemo(() => Object.keys(columnVisibility).filter((key) => !columnVisibility[key]), [columnVisibility]);
|
||||||
() => Object.keys(columnVisibility).filter((key) => !columnVisibility[key]),
|
|
||||||
[columnVisibility],
|
|
||||||
);
|
|
||||||
|
|
||||||
//TO DO: сделать
|
|
||||||
const { addColorForCells } = {};
|
|
||||||
|
|
||||||
const handleChangeShowColumnFilters = useCallback(() => {
|
const handleChangeShowColumnFilters = useCallback(() => {
|
||||||
onChangeShowColumnFilters(!showColumnFilters);
|
onChangeShowColumnFilters(!showColumnFilters);
|
||||||
@ -102,10 +96,7 @@ const SettingPanel = ({
|
|||||||
isPinned ? onUnpinColumn?.(selectedColumnId) : onPinColumn?.(selectedColumnId);
|
isPinned ? onUnpinColumn?.(selectedColumnId) : onPinColumn?.(selectedColumnId);
|
||||||
}, [isPinned, onPinColumn, onUnpinColumn, selectedColumnId]);
|
}, [isPinned, onPinColumn, onUnpinColumn, selectedColumnId]);
|
||||||
const leafColumns = useMemo(() => collectLeafColumns({ columns }), [columns]);
|
const leafColumns = useMemo(() => collectLeafColumns({ columns }), [columns]);
|
||||||
const stageColumnIds = useMemo(
|
const stageColumnIds = useMemo(() => new Set([...stageColumnsHiddenFromPicker, ...(columnsCurStage || [])]), [columnsCurStage]);
|
||||||
() => new Set([...stageColumnsHiddenFromPicker, ...(columnsCurStage || [])]),
|
|
||||||
[columnsCurStage],
|
|
||||||
);
|
|
||||||
const showOnlyCurrentStageColumns = useMemo(() => {
|
const showOnlyCurrentStageColumns = useMemo(() => {
|
||||||
if (!columnsCurStage?.length || !leafColumns.length) return false;
|
if (!columnsCurStage?.length || !leafColumns.length) return false;
|
||||||
return leafColumns.every((column) =>
|
return leafColumns.every((column) =>
|
||||||
@ -125,6 +116,14 @@ const SettingPanel = ({
|
|||||||
onSetColumnsVisibility(visibilityByColumnId);
|
onSetColumnsVisibility(visibilityByColumnId);
|
||||||
}, [columnsCurStage, leafColumns, onSetColumnsVisibility, showOnlyCurrentStageColumns, stageColumnIds]);
|
}, [columnsCurStage, leafColumns, onSetColumnsVisibility, showOnlyCurrentStageColumns, stageColumnIds]);
|
||||||
|
|
||||||
|
const handleSetAllColumnsVisibility = useCallback(
|
||||||
|
(columnIds, isVisible) => {
|
||||||
|
const visibilityByColumnId = Object.fromEntries(columnIds.map((columnId) => [columnId, isVisible]));
|
||||||
|
onSetColumnsVisibility(visibilityByColumnId);
|
||||||
|
},
|
||||||
|
[onSetColumnsVisibility],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Panel data-pin-panel>
|
<Panel data-pin-panel>
|
||||||
@ -145,7 +144,6 @@ const SettingPanel = ({
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</GroupByObject>
|
</GroupByObject>
|
||||||
|
|
||||||
|
|
||||||
<Divider orientation='vertical' flexItem />
|
<Divider orientation='vertical' flexItem />
|
||||||
<GroupByObject title='Строки'>
|
<GroupByObject title='Строки'>
|
||||||
{!isFormNoCanAddRow && (
|
{!isFormNoCanAddRow && (
|
||||||
@ -193,7 +191,12 @@ const SettingPanel = ({
|
|||||||
<Divider orientation='vertical' flexItem />
|
<Divider orientation='vertical' flexItem />
|
||||||
<GroupByObject title='Столбцы'>
|
<GroupByObject title='Столбцы'>
|
||||||
{columns ? (
|
{columns ? (
|
||||||
<CollapsibleTree columnTree={columns} onSelectNode={onToggleColumnVisibility} selectedIds={selectedColumnIds} />
|
<CollapsibleTree
|
||||||
|
columnTree={columns}
|
||||||
|
onSelectNode={onToggleColumnVisibility}
|
||||||
|
onSelectAllNodes={handleSetAllColumnsVisibility}
|
||||||
|
selectedIds={selectedColumnIds}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
''
|
''
|
||||||
)}
|
)}
|
||||||
@ -204,8 +207,7 @@ const SettingPanel = ({
|
|||||||
color='success'
|
color='success'
|
||||||
data-active={showOnlyCurrentStageColumns}
|
data-active={showOnlyCurrentStageColumns}
|
||||||
onClick={handleToggleCurrentStageColumns}
|
onClick={handleToggleCurrentStageColumns}
|
||||||
disabled={!columnsCurStage || columnsCurStage.length === 0}
|
disabled={!columnsCurStage || columnsCurStage.length === 0}>
|
||||||
>
|
|
||||||
{showOnlyCurrentStageColumns ? <AllStageColumns /> : <CurrentStageColumns />}
|
{showOnlyCurrentStageColumns ? <AllStageColumns /> : <CurrentStageColumns />}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
@ -241,7 +243,7 @@ const SettingPanel = ({
|
|||||||
</GroupByObject>
|
</GroupByObject>
|
||||||
</Stack>
|
</Stack>
|
||||||
<ValidationErrorsAlert errors={validationErrors} onNavigateToColumn={onNavigateToColumn} />
|
<ValidationErrorsAlert errors={validationErrors} onNavigateToColumn={onNavigateToColumn} />
|
||||||
</Panel >
|
</Panel>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
|
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
|
||||||
import WarningAmberRoundedIcon from '@mui/icons-material/WarningAmberRounded';
|
import WarningAmberRoundedIcon from '@mui/icons-material/WarningAmberRounded';
|
||||||
import { Button, Menu, MenuItem, Stack } from '@mui/material';
|
import { Button, Menu, MenuItem, Stack } from '@mui/material';
|
||||||
import { useEffect, useState } from 'react';
|
import { memo, useEffect, useState } from 'react';
|
||||||
|
|
||||||
const warningColors = {
|
const warningColors = {
|
||||||
bg: '#fff7e6',
|
bg: '#fff7e6',
|
||||||
@ -115,4 +115,4 @@ const ValidationErrorsAlert = ({ errors = [], onNavigateToColumn }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ValidationErrorsAlert;
|
export default memo(ValidationErrorsAlert);
|
||||||
|
|||||||
@ -1,32 +1,32 @@
|
|||||||
import { Box, Slider } from '@mui/material';
|
import { Box, Slider } from '@mui/material';
|
||||||
import { useState } from 'react';
|
import { memo } from 'react';
|
||||||
|
|
||||||
|
const sliderContainerSx = { width: 200, height: '2.5rem', display: 'flex', alignItems: 'center', gap: 2 };
|
||||||
|
const zoomMarks = [
|
||||||
|
{ value: 0.5, label: '50%' },
|
||||||
|
{ value: 1, label: '100%' },
|
||||||
|
{ value: 2, label: '200%' },
|
||||||
|
];
|
||||||
|
|
||||||
const ZoomSlider = ({ onChange, width = 200, curScale }) => {
|
const ZoomSlider = ({ onChange, width = 200, curScale }) => {
|
||||||
const [scale, setScale] = useState(curScale);
|
const handleChange = (_event, newValue) => {
|
||||||
|
|
||||||
const handleChange = (event, newValue) => {
|
|
||||||
setScale(newValue);
|
|
||||||
if (onChange) onChange(newValue);
|
if (onChange) onChange(newValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ width, height: '2.5rem', display: 'flex', alignItems: 'center', gap: 2 }}>
|
<Box sx={width === 200 ? sliderContainerSx : { ...sliderContainerSx, width }}>
|
||||||
<Slider
|
<Slider
|
||||||
value={scale}
|
value={curScale}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
min={0.5}
|
min={0.5}
|
||||||
max={2}
|
max={2}
|
||||||
step={0.01}
|
step={0.01}
|
||||||
valueLabelDisplay='auto'
|
valueLabelDisplay='auto'
|
||||||
valueLabelFormat={(value) => `${Math.round(value * 100)}%`}
|
valueLabelFormat={(value) => `${Math.round(value * 100)}%`}
|
||||||
marks={[
|
marks={zoomMarks}
|
||||||
{ value: 0.5, label: '50%' },
|
|
||||||
{ value: 1, label: '100%' },
|
|
||||||
{ value: 2, label: '200%' },
|
|
||||||
]}
|
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ZoomSlider;
|
export default memo(ZoomSlider);
|
||||||
|
|||||||
@ -2,11 +2,7 @@ import React, { useMemo } from 'react';
|
|||||||
import ColumnResizer from './ColumnResizer';
|
import ColumnResizer from './ColumnResizer';
|
||||||
|
|
||||||
const getSortedColumns = (table) => {
|
const getSortedColumns = (table) => {
|
||||||
return [
|
return [...table.getLeftVisibleLeafColumns(), ...table.getCenterVisibleLeafColumns(), ...table.getRightVisibleLeafColumns()];
|
||||||
...table.getLeftVisibleLeafColumns(),
|
|
||||||
...table.getCenterVisibleLeafColumns(),
|
|
||||||
...table.getRightVisibleLeafColumns(),
|
|
||||||
];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getColumnPinnedStyles = (column) => {
|
const getColumnPinnedStyles = (column) => {
|
||||||
@ -113,10 +109,7 @@ const HeaderCell = ({ header, table, pinningPosition, onClick, onChangeWidth })
|
|||||||
const headerSize = header.getSize();
|
const headerSize = header.getSize();
|
||||||
const isPinned = Boolean(pinningPosition);
|
const isPinned = Boolean(pinningPosition);
|
||||||
const leftOffset = pinningPosition === 'left' ? header.getStart() : undefined;
|
const leftOffset = pinningPosition === 'left' ? header.getStart() : undefined;
|
||||||
const rightOffset =
|
const rightOffset = pinningPosition === 'right' ? table.getRightTotalSize() - header.getStart() - headerSize : undefined;
|
||||||
pinningPosition === 'right'
|
|
||||||
? table.getRightTotalSize() - header.getStart() - headerSize
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const customBgColor = column.columnDef?.muiTableHeadCellProps?.sx?.backgroundColor;
|
const customBgColor = column.columnDef?.muiTableHeadCellProps?.sx?.backgroundColor;
|
||||||
|
|
||||||
@ -200,14 +193,14 @@ const FilterRow = ({ table }) => {
|
|||||||
backgroundColor: 'white',
|
backgroundColor: 'white',
|
||||||
}}>
|
}}>
|
||||||
{filteredColumns.map((column) => (
|
{filteredColumns.map((column) => (
|
||||||
<FilterCell key={`filter-${column.id}`} column={column} table={table} />
|
<FilterCell key={`filter-${column.id}`} column={column} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Компонент ячейки фильтра
|
// Компонент ячейки фильтра
|
||||||
const FilterCell = ({ column, table }) => {
|
const FilterCell = ({ column }) => {
|
||||||
const { isPinned, left, right } = getColumnPinnedStyles(column);
|
const { isPinned, left, right } = getColumnPinnedStyles(column);
|
||||||
|
|
||||||
// Определяем тип фильтра на основе колонки
|
// Определяем тип фильтра на основе колонки
|
||||||
|
|||||||
@ -1,16 +1,7 @@
|
|||||||
import {
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||||
createContext,
|
import { toast } from 'react-toastify';
|
||||||
useCallback,
|
import { useWebSocket } from '../hooks/useWebSocket';
|
||||||
useContext,
|
import { getRowId } from '../utils/rowUtils';
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
useRef,
|
|
||||||
useState,
|
|
||||||
useSyncExternalStore,
|
|
||||||
} from "react";
|
|
||||||
import { toast } from "react-toastify";
|
|
||||||
import { useWebSocket } from "../hooks/useWebSocket";
|
|
||||||
import { getRowId } from "../utils/rowUtils";
|
|
||||||
|
|
||||||
const RealtimeActionsContext = createContext(null);
|
const RealtimeActionsContext = createContext(null);
|
||||||
const RealtimeConnectionContext = createContext(null);
|
const RealtimeConnectionContext = createContext(null);
|
||||||
@ -27,47 +18,55 @@ const useRequiredContext = (context, hookName) => {
|
|||||||
|
|
||||||
const createLockedCellsStore = () => {
|
const createLockedCellsStore = () => {
|
||||||
let cells = new Set();
|
let cells = new Set();
|
||||||
const listeners = new Set();
|
const listenersByCell = new Map();
|
||||||
|
|
||||||
const subscribe = (listener) => {
|
const subscribeCell = (cellKey, listener) => {
|
||||||
|
const listeners = listenersByCell.get(cellKey) || new Set();
|
||||||
listeners.add(listener);
|
listeners.add(listener);
|
||||||
return () => listeners.delete(listener);
|
listenersByCell.set(cellKey, listeners);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
if (listeners.size === 0) listenersByCell.delete(cellKey);
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const setCells = (nextValue) => {
|
const setCells = (nextValue) => {
|
||||||
const currentCells = [...cells];
|
const currentCells = [...cells];
|
||||||
const resolvedValue = typeof nextValue === "function" ? nextValue(currentCells) : nextValue;
|
const resolvedValue = typeof nextValue === 'function' ? nextValue(currentCells) : nextValue;
|
||||||
const nextCells = new Set(resolvedValue || []);
|
const nextCells = new Set(resolvedValue || []);
|
||||||
const hasChanges =
|
const changedCells = new Set([
|
||||||
nextCells.size !== cells.size || [...nextCells].some((cellKey) => !cells.has(cellKey));
|
...[...cells].filter((cellKey) => !nextCells.has(cellKey)),
|
||||||
|
...[...nextCells].filter((cellKey) => !cells.has(cellKey)),
|
||||||
|
]);
|
||||||
|
|
||||||
if (!hasChanges) return;
|
if (changedCells.size === 0) return;
|
||||||
cells = nextCells;
|
cells = nextCells;
|
||||||
listeners.forEach((listener) => listener());
|
changedCells.forEach((cellKey) => {
|
||||||
|
listenersByCell.get(cellKey)?.forEach((listener) => listener());
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
subscribe,
|
subscribeCell,
|
||||||
setCells,
|
setCells,
|
||||||
hasCell: (cellKey) => cells.has(cellKey),
|
hasCell: (cellKey) => cells.has(cellKey),
|
||||||
getCells: () => [...cells],
|
getCells: () => [...cells],
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useRealtimeActions = () =>
|
export const useRealtimeActions = () => useRequiredContext(RealtimeActionsContext, 'useRealtimeActions');
|
||||||
useRequiredContext(RealtimeActionsContext, "useRealtimeActions");
|
|
||||||
|
|
||||||
export const useRealtimeConnection = () =>
|
export const useRealtimeConnection = () => useRequiredContext(RealtimeConnectionContext, 'useRealtimeConnection');
|
||||||
useRequiredContext(RealtimeConnectionContext, "useRealtimeConnection");
|
|
||||||
|
|
||||||
export const useVspOptions = () =>
|
export const useVspOptions = () => useRequiredContext(RealtimeVspOptionsContext, 'useVspOptions');
|
||||||
useRequiredContext(RealtimeVspOptionsContext, "useVspOptions");
|
|
||||||
|
|
||||||
export const useCellLock = (cellKey) => {
|
export const useCellLock = (cellKey) => {
|
||||||
const store = useRequiredContext(LockedCellsStoreContext, "useCellLock");
|
const store = useRequiredContext(LockedCellsStoreContext, 'useCellLock');
|
||||||
|
const subscribe = useCallback((listener) => store.subscribeCell(cellKey, listener), [cellKey, store]);
|
||||||
const getSnapshot = useCallback(() => store.hasCell(cellKey), [cellKey, store]);
|
const getSnapshot = useCallback(() => store.hasCell(cellKey), [cellKey, store]);
|
||||||
|
|
||||||
return useSyncExternalStore(store.subscribe, getSnapshot, () => false);
|
return useSyncExternalStore(subscribe, getSnapshot, () => false);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useRealtime = () => {
|
export const useRealtime = () => {
|
||||||
@ -78,24 +77,13 @@ export const useRealtime = () => {
|
|||||||
return { ...actions, ...connection, vspOptions };
|
return { ...actions, ...connection, vspOptions };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const RealtimeProvider = ({
|
export const RealtimeProvider = ({ children, formId, sheetName, direction, year, isProject = false }) => {
|
||||||
children,
|
|
||||||
formId,
|
|
||||||
sheetName,
|
|
||||||
direction,
|
|
||||||
year,
|
|
||||||
userId,
|
|
||||||
isProject = false,
|
|
||||||
}) => {
|
|
||||||
// Формируем URL (кастомные секреты на фронте пока недоступны, делаем через REACT_APP_ROOT_PATH)
|
// Формируем URL (кастомные секреты на фронте пока недоступны, делаем через REACT_APP_ROOT_PATH)
|
||||||
const wsUrl = `${(
|
const wsUrl = `${(
|
||||||
process.env.REACT_APP_API_URL ||
|
process.env.REACT_APP_API_URL || process.env.REACT_APP_API_URL || process.env.REACT_APP_ROOT_PATH || 'ws://localhost:8000'
|
||||||
process.env.REACT_APP_API_URL ||
|
).replace(/^http/, 'ws')}${
|
||||||
process.env.REACT_APP_ROOT_PATH ||
|
|
||||||
"ws://localhost:8000"
|
|
||||||
).replace(/^http/, "ws")}${
|
|
||||||
!isProject
|
!isProject
|
||||||
? `/api/v1/ws/form/${formId}/sheet/${sheetName}${direction ? `?direction=${direction}` : ""}`
|
? `/api/v1/ws/form/${formId}/sheet/${sheetName}${direction ? `?direction=${direction}` : ''}`
|
||||||
: `/api/v1/ws/projects/${formId}/report/${year}/${sheetName}`
|
: `/api/v1/ws/projects/${formId}/report/${year}/${sheetName}`
|
||||||
}`;
|
}`;
|
||||||
|
|
||||||
@ -104,73 +92,71 @@ export const RealtimeProvider = ({
|
|||||||
if (lockedCellsStoreRef.current === null) {
|
if (lockedCellsStoreRef.current === null) {
|
||||||
lockedCellsStoreRef.current = createLockedCellsStore();
|
lockedCellsStoreRef.current = createLockedCellsStore();
|
||||||
}
|
}
|
||||||
|
const lockedCellsStore = lockedCellsStoreRef.current;
|
||||||
|
|
||||||
const handleMessage = useCallback((data) => {
|
const handleMessage = useCallback((data) => {
|
||||||
// Обработка ошибок
|
// Обработка ошибок
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
console.log(data.error.message);
|
console.log(data.error.message);
|
||||||
toast.error(`Server error:${data.error.message}` || "");
|
toast.error(`Server error:${data.error.message}` || '');
|
||||||
onErrorRef.current?.(data.error);
|
onErrorRef.current?.(data.error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (data.event) {
|
switch (data.event) {
|
||||||
case "cell_edit_start":
|
case 'cell_edit_start':
|
||||||
console.log("Cell edit started:", data);
|
console.log('Cell edit started:', data);
|
||||||
if (onCellEditStartRef.current) {
|
if (onCellEditStartRef.current) {
|
||||||
onCellEditStartRef.current(data);
|
onCellEditStartRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "cell_edit_end":
|
case 'cell_edit_end':
|
||||||
console.log("Cell edit ended:", data);
|
console.log('Cell edit ended:', data);
|
||||||
if (onCellEditEndRef.current) {
|
if (onCellEditEndRef.current) {
|
||||||
onCellEditEndRef.current(data);
|
onCellEditEndRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "cell_updated":
|
case 'cell_updated':
|
||||||
if (data.result && onCellUpdateRef.current) {
|
if (data.result && onCellUpdateRef.current) {
|
||||||
const updatedCells = Array.isArray(data.result)
|
const updatedCells = Array.isArray(data.result) ? data.result : [data.result];
|
||||||
? data.result
|
|
||||||
: [data.result];
|
|
||||||
onCellUpdateRef.current(updatedCells);
|
onCellUpdateRef.current(updatedCells);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "row_added":
|
case 'row_added':
|
||||||
if (data.result && onRowAddRef.current) {
|
if (data.result && onRowAddRef.current) {
|
||||||
onRowAddRef.current(data);
|
onRowAddRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "row_deleted":
|
case 'row_deleted':
|
||||||
if (data.result && onRowDeleteRef.current) {
|
if (data.result && onRowDeleteRef.current) {
|
||||||
onRowDeleteRef.current(data);
|
onRowDeleteRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "program_added":
|
case 'program_added':
|
||||||
console.log("Program added:", data);
|
console.log('Program added:', data);
|
||||||
if (data.result && onProgramAddRef.current) {
|
if (data.result && onProgramAddRef.current) {
|
||||||
onProgramAddRef.current(data);
|
onProgramAddRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "project_added":
|
case 'project_added':
|
||||||
console.log("Project added:", data);
|
console.log('Project added:', data);
|
||||||
if (data.result && onProjectAddRef.current) {
|
if (data.result && onProjectAddRef.current) {
|
||||||
onProjectAddRef.current(data);
|
onProjectAddRef.current(data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
console.log("Unknown event:", data.event);
|
console.log('Unknown event:', data.event);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const { isConnectedRef, isConnected, sendMessage, disconnect, lastError } =
|
const { isConnectedRef, isConnected, sendMessage } = useWebSocket(wsUrl, handleMessage);
|
||||||
useWebSocket(wsUrl, handleMessage);
|
|
||||||
|
|
||||||
const onCellUpdateRef = useRef(null);
|
const onCellUpdateRef = useRef(null);
|
||||||
const onRowAddRef = useRef(null);
|
const onRowAddRef = useRef(null);
|
||||||
@ -182,21 +168,20 @@ export const RealtimeProvider = ({
|
|||||||
const onCellEditStartRef = useRef(null);
|
const onCellEditStartRef = useRef(null);
|
||||||
const onCellEditEndRef = useRef(null);
|
const onCellEditEndRef = useRef(null);
|
||||||
const authAttemptedRef = useRef(false);
|
const authAttemptedRef = useRef(false);
|
||||||
const reconnectTimerRef = useRef(null);
|
|
||||||
|
|
||||||
// Функция для получения токена из localStorage
|
// Функция для получения токена из localStorage
|
||||||
const getAccessToken = useCallback(() => {
|
const getAccessToken = useCallback(() => {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem("access_token");
|
const token = localStorage.getItem('access_token');
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
console.warn("No access token found in localStorage");
|
console.warn('No access token found in localStorage');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return token;
|
return token;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error reading token from localStorage:", error);
|
console.error('Error reading token from localStorage:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
@ -204,13 +189,13 @@ export const RealtimeProvider = ({
|
|||||||
const sendLogin = useCallback(() => {
|
const sendLogin = useCallback(() => {
|
||||||
const token = getAccessToken();
|
const token = getAccessToken();
|
||||||
if (!token) {
|
if (!token) {
|
||||||
console.error("Cannot login: no token available");
|
console.error('Cannot login: no token available');
|
||||||
onErrorRef.current?.("Токен авторизации не найден");
|
onErrorRef.current?.('Токен авторизации не найден');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loginMessage = {
|
const loginMessage = {
|
||||||
event: "user_login",
|
event: 'user_login',
|
||||||
data: { token },
|
data: { token },
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -220,10 +205,11 @@ export const RealtimeProvider = ({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isConnected && !authAttemptedRef.current) {
|
if (isConnected && !authAttemptedRef.current) {
|
||||||
authAttemptedRef.current = true;
|
authAttemptedRef.current = true;
|
||||||
console.log("WebSocket connected, sending login...");
|
console.log('WebSocket connected, sending login...');
|
||||||
setTimeout(() => {
|
const timeoutId = setTimeout(() => {
|
||||||
sendLogin();
|
sendLogin();
|
||||||
}, 100);
|
}, 100);
|
||||||
|
return () => clearTimeout(timeoutId);
|
||||||
}
|
}
|
||||||
}, [isConnected, sendLogin]);
|
}, [isConnected, sendLogin]);
|
||||||
|
|
||||||
@ -233,27 +219,29 @@ export const RealtimeProvider = ({
|
|||||||
}
|
}
|
||||||
}, [isConnected]);
|
}, [isConnected]);
|
||||||
|
|
||||||
const addCommonField = (message) => {
|
const addCommonField = useCallback(
|
||||||
if (isProject) {
|
(message) => {
|
||||||
message.report_type = sheetName;
|
if (isProject) {
|
||||||
message.project_id = formId;
|
message.report_type = sheetName;
|
||||||
message.year = year;
|
message.project_id = formId;
|
||||||
} else {
|
message.year = year;
|
||||||
message.sheet = sheetName;
|
} else {
|
||||||
message.form_id = formId;
|
message.sheet = sheetName;
|
||||||
message.direction = direction;
|
message.form_id = formId;
|
||||||
}
|
message.direction = direction;
|
||||||
return message;
|
}
|
||||||
};
|
return message;
|
||||||
|
},
|
||||||
|
[direction, formId, isProject, sheetName, year],
|
||||||
|
);
|
||||||
|
|
||||||
// Функция для начала редактирования ячейки
|
// Функция для начала редактирования ячейки
|
||||||
const startEditing = useCallback(
|
const startEditing = useCallback(
|
||||||
async (row, column) => {
|
(row, column) => {
|
||||||
const columnId = column.id;
|
const columnId = column.id;
|
||||||
const rowId = row.id;
|
|
||||||
|
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("WebSocket не подключен");
|
onErrorRef.current?.('WebSocket не подключен');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -261,7 +249,7 @@ export const RealtimeProvider = ({
|
|||||||
const colId = columnId.slice(5); // убираем префикс "data."
|
const colId = columnId.slice(5); // убираем префикс "data."
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "cell_edit_start",
|
event: 'cell_edit_start',
|
||||||
data: {
|
data: {
|
||||||
line_id: lineId,
|
line_id: lineId,
|
||||||
column: colId,
|
column: colId,
|
||||||
@ -275,17 +263,16 @@ export const RealtimeProvider = ({
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage],
|
[isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Функция для завершения редактирования ячейки
|
// Функция для завершения редактирования ячейки
|
||||||
const endEditing = useCallback(
|
const endEditing = useCallback(
|
||||||
async (row, column) => {
|
(row, column) => {
|
||||||
const columnId = column.id;
|
const columnId = column.id;
|
||||||
const rowId = row.id;
|
|
||||||
|
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("WebSocket не подключен");
|
onErrorRef.current?.('WebSocket не подключен');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -293,7 +280,7 @@ export const RealtimeProvider = ({
|
|||||||
const colId = columnId.slice(5);
|
const colId = columnId.slice(5);
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "cell_edit_end",
|
event: 'cell_edit_end',
|
||||||
data: {
|
data: {
|
||||||
line_id: lineId,
|
line_id: lineId,
|
||||||
column: colId,
|
column: colId,
|
||||||
@ -307,22 +294,21 @@ export const RealtimeProvider = ({
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage],
|
[isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const updateCell = useCallback(
|
const updateCell = useCallback(
|
||||||
async (row, column, value) => {
|
(row, column, value) => {
|
||||||
const columnId = column.id;
|
const columnId = column.id;
|
||||||
const rowId = row.id;
|
if (!isConnectedRef.current) {
|
||||||
if (!isConnectedRef) {
|
onErrorRef.current?.('WebSocket не подключен');
|
||||||
onErrorRef.current?.("WebSocket не подключен");
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lineId = getRowId(row);
|
const lineId = getRowId(row);
|
||||||
const colId = columnId.slice(5);
|
const colId = columnId.slice(5);
|
||||||
const message = {
|
const message = {
|
||||||
event: "cell_updated",
|
event: 'cell_updated',
|
||||||
data: {
|
data: {
|
||||||
line_id: lineId,
|
line_id: lineId,
|
||||||
line_id_code: row.id,
|
line_id_code: row.id,
|
||||||
@ -338,79 +324,79 @@ export const RealtimeProvider = ({
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage],
|
[isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addRow = useCallback(
|
const addRow = useCallback(
|
||||||
async (rowData) => {
|
(rowData) => {
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("Нет подключения или авторизации");
|
onErrorRef.current?.('Нет подключения или авторизации');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "row_added",
|
event: 'row_added',
|
||||||
data: rowData,
|
data: rowData,
|
||||||
};
|
};
|
||||||
addCommonField(message);
|
addCommonField(message);
|
||||||
|
|
||||||
return sendMessage(message);
|
return sendMessage(message);
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage, sheetName, formId, direction],
|
[addCommonField, isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addProject = useCallback(
|
const addProject = useCallback(
|
||||||
async (rowData) => {
|
(rowData) => {
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("Нет подключения или авторизации");
|
onErrorRef.current?.('Нет подключения или авторизации');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "project_added",
|
event: 'project_added',
|
||||||
data: rowData,
|
data: rowData,
|
||||||
};
|
};
|
||||||
addCommonField(message);
|
addCommonField(message);
|
||||||
|
|
||||||
return sendMessage(message);
|
return sendMessage(message);
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage, sheetName, formId, direction],
|
[addCommonField, isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addProgram = useCallback(
|
const addProgram = useCallback(
|
||||||
async (rowData) => {
|
(rowData) => {
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("Нет подключения или авторизации");
|
onErrorRef.current?.('Нет подключения или авторизации');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "program_added",
|
event: 'program_added',
|
||||||
data: rowData,
|
data: rowData,
|
||||||
};
|
};
|
||||||
addCommonField(message);
|
addCommonField(message);
|
||||||
|
|
||||||
return sendMessage(message);
|
return sendMessage(message);
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage, sheetName, formId, direction],
|
[addCommonField, isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const deleteRow = useCallback(
|
const deleteRow = useCallback(
|
||||||
async (rowId) => {
|
(rowId) => {
|
||||||
if (!isConnectedRef) {
|
if (!isConnectedRef.current) {
|
||||||
onErrorRef.current?.("Нет подключения или авторизации");
|
onErrorRef.current?.('Нет подключения или авторизации');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = {
|
const message = {
|
||||||
event: "row_deleted",
|
event: 'row_deleted',
|
||||||
data: { row_id: rowId },
|
data: { row_id: rowId },
|
||||||
};
|
};
|
||||||
addCommonField(message);
|
addCommonField(message);
|
||||||
|
|
||||||
return sendMessage(message);
|
return sendMessage(message);
|
||||||
},
|
},
|
||||||
[isConnected, sendMessage, sheetName, formId, direction],
|
[addCommonField, isConnectedRef, sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const subscribeToCellUpdates = useCallback((callback) => {
|
const subscribeToCellUpdates = useCallback((callback) => {
|
||||||
@ -477,42 +463,65 @@ export const RealtimeProvider = ({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const retryLogin = useCallback(() => {
|
const retryLogin = useCallback(() => {
|
||||||
if (isConnected) {
|
if (isConnectedRef.current) {
|
||||||
authAttemptedRef.current = false;
|
authAttemptedRef.current = false;
|
||||||
sendLogin();
|
sendLogin();
|
||||||
}
|
}
|
||||||
}, [isConnected, sendLogin]);
|
}, [isConnectedRef, sendLogin]);
|
||||||
|
|
||||||
|
const actions = useMemo(
|
||||||
|
() => ({
|
||||||
|
startEditing,
|
||||||
|
endEditing,
|
||||||
|
updateCell,
|
||||||
|
addRow,
|
||||||
|
addProgram,
|
||||||
|
addProject,
|
||||||
|
deleteRow,
|
||||||
|
subscribeToRowAdds,
|
||||||
|
subscribeToRowDeletes,
|
||||||
|
subscribeToProgramAdds,
|
||||||
|
subscribeToProjectAdds,
|
||||||
|
subscribeToErrors,
|
||||||
|
subscribeToAuthSuccess,
|
||||||
|
subscribeToCellEditStart,
|
||||||
|
subscribeToCellEditEnd,
|
||||||
|
subscribeToCellUpdates,
|
||||||
|
retryLogin,
|
||||||
|
setLockedCells: lockedCellsStore.setCells,
|
||||||
|
setVspOptions,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
addProgram,
|
||||||
|
addProject,
|
||||||
|
addRow,
|
||||||
|
deleteRow,
|
||||||
|
endEditing,
|
||||||
|
lockedCellsStore,
|
||||||
|
retryLogin,
|
||||||
|
startEditing,
|
||||||
|
subscribeToAuthSuccess,
|
||||||
|
subscribeToCellEditEnd,
|
||||||
|
subscribeToCellEditStart,
|
||||||
|
subscribeToCellUpdates,
|
||||||
|
subscribeToErrors,
|
||||||
|
subscribeToProgramAdds,
|
||||||
|
subscribeToProjectAdds,
|
||||||
|
subscribeToRowAdds,
|
||||||
|
subscribeToRowDeletes,
|
||||||
|
updateCell,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const connection = useMemo(() => ({ isConnected }), [isConnected]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RealtimeContext.Provider
|
<RealtimeActionsContext.Provider value={actions}>
|
||||||
value={{
|
<RealtimeConnectionContext.Provider value={connection}>
|
||||||
isConnected,
|
<RealtimeVspOptionsContext.Provider value={vspOptions}>
|
||||||
error: lastError,
|
<LockedCellsStoreContext.Provider value={lockedCellsStore}>{children}</LockedCellsStoreContext.Provider>
|
||||||
startEditing,
|
</RealtimeVspOptionsContext.Provider>
|
||||||
endEditing,
|
</RealtimeConnectionContext.Provider>
|
||||||
updateCell,
|
</RealtimeActionsContext.Provider>
|
||||||
addRow,
|
|
||||||
addProgram,
|
|
||||||
addProject,
|
|
||||||
deleteRow,
|
|
||||||
subscribeToRowAdds,
|
|
||||||
subscribeToRowDeletes,
|
|
||||||
subscribeToProgramAdds,
|
|
||||||
subscribeToProjectAdds,
|
|
||||||
subscribeToErrors,
|
|
||||||
subscribeToAuthSuccess,
|
|
||||||
subscribeToCellEditStart,
|
|
||||||
subscribeToCellEditEnd,
|
|
||||||
subscribeToCellUpdates,
|
|
||||||
retryLogin,
|
|
||||||
lockedCells,
|
|
||||||
setLockedCells,
|
|
||||||
vspOptions,
|
|
||||||
setVspOptions,
|
|
||||||
releaseAllLocks: () => releaseAllLocks(userId),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</RealtimeContext.Provider>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@ -33,7 +33,10 @@ export const useColumnSettings = (tableKey) => {
|
|||||||
}, [tableKey]);
|
}, [tableKey]);
|
||||||
|
|
||||||
const handlePinColumn = useCallback((colId) => {
|
const handlePinColumn = useCallback((colId) => {
|
||||||
setColumnPinning((prev) => ({ ...prev, left: [...prev.left, colId] }));
|
setColumnPinning((prev) => {
|
||||||
|
if (!colId || prev.left.includes(colId)) return prev;
|
||||||
|
return { ...prev, left: [...prev.left, colId] };
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleUnpinColumn = useCallback((colId) => {
|
const handleUnpinColumn = useCallback((colId) => {
|
||||||
@ -63,11 +66,18 @@ export const useColumnSettings = (tableKey) => {
|
|||||||
return acc;
|
return acc;
|
||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
setColumnVisibility((prev) => ({ ...prev, ...leafCols }));
|
setColumnVisibility((prev) => {
|
||||||
|
const hasChanges = Object.entries(leafCols).some(([columnId, isVisible]) => prev[columnId] !== isVisible);
|
||||||
|
return hasChanges ? { ...prev, ...leafCols } : prev;
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSetColumnsVisibility = useCallback((visibilityByColumnId) => {
|
const handleSetColumnsVisibility = useCallback((visibilityByColumnId) => {
|
||||||
setColumnVisibility((prev) => ({ ...prev, ...visibilityByColumnId }));
|
setColumnVisibility((prev) => {
|
||||||
|
const entries = Object.entries(visibilityByColumnId);
|
||||||
|
const hasChanges = entries.some(([columnId, isVisible]) => prev[columnId] !== isVisible);
|
||||||
|
return hasChanges ? { ...prev, ...visibilityByColumnId } : prev;
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Опционально: функция для сброса всех настроек
|
// Опционально: функция для сброса всех настроек
|
||||||
|
|||||||
@ -1,29 +1,54 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useEffect, useState } from 'react';
|
||||||
import { toast } from "react-toastify";
|
import { toast } from 'react-toastify';
|
||||||
import { FormsSheetApi } from "../../../api/form_sheet";
|
import { FormsSheetApi } from '../../../api/form_sheet';
|
||||||
import { ProjectsApi } from "../../../api/projects";
|
import { ProjectsApi } from '../../../api/projects';
|
||||||
import { useRealtime } from "../contexts/RealtimeContext";
|
import { useRealtimeActions, useRealtimeConnection } from '../contexts/RealtimeContext';
|
||||||
import {
|
import { addRootRow, deleteRow, insertCell, insertProjectRow, updateCells } from '../utils/cellUtils';
|
||||||
addRootRow,
|
import { getParentId, isVspNewRow } from '../utils/rowUtils';
|
||||||
deleteRow,
|
|
||||||
insertCell,
|
const ROW_TYPE_LEVELS = {
|
||||||
insertProjectRow,
|
ROOT: 0,
|
||||||
updateCells,
|
GROUP: 1,
|
||||||
} from "../utils/cellUtils";
|
ITEM: 2,
|
||||||
import { getParentId, isVspNewRow } from "../utils/rowUtils";
|
SUB_ITEM: 3,
|
||||||
|
INPUT: 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildHierarchy = (items) => {
|
||||||
|
const result = [];
|
||||||
|
const stack = [];
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const currentLevel = ROW_TYPE_LEVELS[item.row_type] ?? 999;
|
||||||
|
|
||||||
|
while (stack.length > 0 && (ROW_TYPE_LEVELS[stack.at(-1).row_type] ?? 999) >= currentLevel) {
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = stack.at(-1);
|
||||||
|
const newNode = { ...item, subRows: [] };
|
||||||
|
|
||||||
|
if (parent) {
|
||||||
|
parent.subRows.push(newNode);
|
||||||
|
} else {
|
||||||
|
result.push(newNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.row_type !== 'INPUT') {
|
||||||
|
stack.push(newNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
||||||
const [data, setData] = useState([]);
|
const [data, setData] = useState([]);
|
||||||
const [columnsCurStage, setColumnsCurStage] = useState([]);
|
const [columnsCurStage, setColumnsCurStage] = useState([]);
|
||||||
const [isConnected, setIsConnected] = useState(false);
|
|
||||||
const [error, setError] = useState(null);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [editingCells, setEditingCells] = useState({});
|
const [editingCells, setEditingCells] = useState({});
|
||||||
const dataRef = useRef(data);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
isConnected: wsConnected,
|
|
||||||
error: wsError,
|
|
||||||
subscribeToCellUpdates,
|
subscribeToCellUpdates,
|
||||||
subscribeToRowAdds,
|
subscribeToRowAdds,
|
||||||
subscribeToProgramAdds,
|
subscribeToProgramAdds,
|
||||||
@ -33,62 +58,19 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
subscribeToCellEditStart,
|
subscribeToCellEditStart,
|
||||||
subscribeToCellEditEnd,
|
subscribeToCellEditEnd,
|
||||||
setLockedCells,
|
setLockedCells,
|
||||||
} = useRealtime();
|
} = useRealtimeActions();
|
||||||
|
const { isConnected: wsConnected } = useRealtimeConnection();
|
||||||
const formatedToSubRows = useCallback((depth, oldData) => {
|
|
||||||
if (depth === 0) return oldData;
|
|
||||||
|
|
||||||
const dataFiltered = oldData.filter((d) => d.depth < depth);
|
|
||||||
|
|
||||||
for (let i = 0; i < dataFiltered.length; i++) {
|
|
||||||
const curRow = dataFiltered[i];
|
|
||||||
|
|
||||||
// Находим следующий элемент на том же или более высоком уровне
|
|
||||||
let nextRow = null;
|
|
||||||
for (let j = i + 1; j < dataFiltered.length; j++) {
|
|
||||||
if (dataFiltered[j].depth <= curRow.depth) {
|
|
||||||
nextRow = dataFiltered[j];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Находим всех потомков для текущей строки
|
|
||||||
const subRows = oldData.filter((d) => {
|
|
||||||
// Потомок должен иметь глубину больше чем у родителя
|
|
||||||
if (d.depth <= curRow.depth) return false;
|
|
||||||
|
|
||||||
// Потомок должен идти после родителя по sort_order
|
|
||||||
if (d.sort_order <= curRow.sort_order) return false;
|
|
||||||
|
|
||||||
// Если есть следующий элемент на том же уровне - потомок должен быть до него
|
|
||||||
if (nextRow && d.sort_order >= nextRow.sort_order) return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (subRows.length > 0) {
|
|
||||||
curRow.subRows = subRows;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Рекурсивно обрабатываем следующий уровень
|
|
||||||
// Находим максимальную глубину в текущем dataFiltered
|
|
||||||
const maxDepth = Math.max(...dataFiltered.map((d) => d.depth));
|
|
||||||
if (maxDepth > 0) {
|
|
||||||
return formatedToSubRows(maxDepth, dataFiltered);
|
|
||||||
}
|
|
||||||
|
|
||||||
return dataFiltered;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Загрузка начальных данных
|
// Загрузка начальных данных
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let isCancelled = false;
|
||||||
|
|
||||||
const loadInitialData = async () => {
|
const loadInitialData = async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
let res;
|
let res;
|
||||||
|
|
||||||
if (formType === "PROJECT") {
|
if (formType === 'PROJECT') {
|
||||||
res = await ProjectsApi.getTableData(formId, sheetName, year);
|
res = await ProjectsApi.getTableData(formId, sheetName, year);
|
||||||
} else if (direction !== null) {
|
} else if (direction !== null) {
|
||||||
res = await FormsSheetApi.get(formId, sheetName, {
|
res = await FormsSheetApi.get(formId, sheetName, {
|
||||||
@ -97,15 +79,12 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
} else {
|
} else {
|
||||||
res = await FormsSheetApi.get(formId, sheetName);
|
res = await FormsSheetApi.get(formId, sheetName);
|
||||||
}
|
}
|
||||||
|
if (isCancelled) return;
|
||||||
|
|
||||||
const data = res.result.filter((d) => d.depth > -1);
|
const data = res.result.filter((d) => d.depth > -1);
|
||||||
const curStageColumns = res.result.filter((d) => d.depth === -1)[0];
|
const curStageColumns = res.result.filter((d) => d.depth === -1)[0];
|
||||||
if (curStageColumns) {
|
const stageColumns = (curStageColumns?.data?.editable || []).map((column) => `data.${column.column}`);
|
||||||
const cols = [];
|
setColumnsCurStage(stageColumns);
|
||||||
for (const col of curStageColumns.data.editable) {
|
|
||||||
cols.push(`data.${col.column}`);
|
|
||||||
}
|
|
||||||
setColumnsCurStage(cols);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!data || data.length === 0) {
|
if (!data || data.length === 0) {
|
||||||
setData([]);
|
setData([]);
|
||||||
@ -115,74 +94,18 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
const hierarchicalData = buildHierarchy(data);
|
const hierarchicalData = buildHierarchy(data);
|
||||||
setData(hierarchicalData);
|
setData(hierarchicalData);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to load initial data:", err);
|
if (!isCancelled) console.error('Failed to load initial data:', err);
|
||||||
setError(err.message);
|
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
if (!isCancelled) setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadInitialData();
|
loadInitialData();
|
||||||
}, [formId, sheetName]);
|
|
||||||
|
|
||||||
const buildHierarchy = (items) => {
|
return () => {
|
||||||
const result = [];
|
isCancelled = true;
|
||||||
const stack = [];
|
|
||||||
|
|
||||||
const getTypeLevel = (type) => {
|
|
||||||
const levels = {
|
|
||||||
ROOT: 0,
|
|
||||||
GROUP: 1,
|
|
||||||
ITEM: 2,
|
|
||||||
SUB_ITEM: 3,
|
|
||||||
INPUT: 4,
|
|
||||||
};
|
|
||||||
return levels[type] ?? 999;
|
|
||||||
};
|
};
|
||||||
|
}, [direction, formId, formType, sheetName, year]);
|
||||||
for (const item of items) {
|
|
||||||
const currentLevel = getTypeLevel(item.row_type);
|
|
||||||
|
|
||||||
while (
|
|
||||||
stack.length > 0 &&
|
|
||||||
getTypeLevel(stack[stack.length - 1].row_type) >= currentLevel
|
|
||||||
) {
|
|
||||||
stack.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
const parent = stack.length > 0 ? stack[stack.length - 1] : null;
|
|
||||||
|
|
||||||
const newNode = { ...item, subRows: [] };
|
|
||||||
|
|
||||||
if (parent) {
|
|
||||||
if (!parent.subRows) {
|
|
||||||
parent.subRows = [];
|
|
||||||
}
|
|
||||||
parent.subRows.push(newNode);
|
|
||||||
} else {
|
|
||||||
result.push(newNode);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Добавляем текущий узел в стек, если он может иметь детей
|
|
||||||
if (item.row_type !== "INPUT") {
|
|
||||||
stack.push(newNode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setIsConnected(wsConnected);
|
|
||||||
}, [wsConnected]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setError(wsError);
|
|
||||||
}, [wsError]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
dataRef.current = data;
|
|
||||||
}, [data]);
|
|
||||||
|
|
||||||
// Подписка на обновления WebSocket
|
// Подписка на обновления WebSocket
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -213,12 +136,12 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
[[], null],
|
[[], null],
|
||||||
);
|
);
|
||||||
if (newRow === null) {
|
if (newRow === null) {
|
||||||
toast.error("Ошибка получения данных");
|
toast.error('Ошибка получения данных');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setData((prevData) => {
|
setData((prevData) => {
|
||||||
let data = structuredClone(prevData);
|
let data = structuredClone(prevData);
|
||||||
if (prevData[0]?.row_type !== "ROOT" && updates[0][0] === 'ROOT') {
|
if (prevData[0]?.row_type !== 'ROOT' && updates[0][0] === 'ROOT') {
|
||||||
const newRowRoot = updates[0];
|
const newRowRoot = updates[0];
|
||||||
data = addRootRow(data, newRowRoot);
|
data = addRootRow(data, newRowRoot);
|
||||||
}
|
}
|
||||||
@ -233,7 +156,7 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
const program_id = data.data.program_id;
|
const program_id = data.data.program_id;
|
||||||
const [updatedCells, newRow] = updates.reduce(
|
const [updatedCells, newRow] = updates.reduce(
|
||||||
(res, row) => {
|
(res, row) => {
|
||||||
if (row[0] === "ITEM") {
|
if (row[0] === 'ITEM') {
|
||||||
res[1] = row;
|
res[1] = row;
|
||||||
} else {
|
} else {
|
||||||
res[0].push(row);
|
res[0].push(row);
|
||||||
@ -243,7 +166,7 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
[[], null],
|
[[], null],
|
||||||
);
|
);
|
||||||
if (newRow === null) {
|
if (newRow === null) {
|
||||||
toast.error("Ошибка получения данных");
|
toast.error('Ошибка получения данных');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setData((prevData) => {
|
setData((prevData) => {
|
||||||
@ -256,7 +179,7 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
const unsubscribeProgramAdds = subscribeToProgramAdds((msg) => {
|
const unsubscribeProgramAdds = subscribeToProgramAdds((msg) => {
|
||||||
let newRow = msg.result[1][0];
|
let newRow = msg.result[1][0];
|
||||||
setData((prevData) => {
|
setData((prevData) => {
|
||||||
const hasRoot = prevData.length > 0 && prevData[0].row_type === "ROOT";
|
const hasRoot = prevData.length > 0 && prevData[0].row_type === 'ROOT';
|
||||||
if (hasRoot) {
|
if (hasRoot) {
|
||||||
newRow = msg.result[1][1];
|
newRow = msg.result[1][1];
|
||||||
}
|
}
|
||||||
@ -291,7 +214,7 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
// Обработчик начала редактирования ячейки
|
// Обработчик начала редактирования ячейки
|
||||||
const unsubscribeCellEditStart = subscribeToCellEditStart((data) => {
|
const unsubscribeCellEditStart = subscribeToCellEditStart((data) => {
|
||||||
const dataCell = data.data;
|
const dataCell = data.data;
|
||||||
dataCell.column = "data." + dataCell.column;
|
dataCell.column = `data.${dataCell.column}`;
|
||||||
if (data.is_self) {
|
if (data.is_self) {
|
||||||
setEditingCells(dataCell);
|
setEditingCells(dataCell);
|
||||||
return;
|
return;
|
||||||
@ -318,9 +241,7 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const unsubscribeErrors = subscribeToErrors((err) => {
|
const unsubscribeErrors = subscribeToErrors((err) => {
|
||||||
console.error("WebSocket error:", err);
|
console.error('WebSocket error:', err);
|
||||||
setError(err);
|
|
||||||
setTimeout(() => setError(null), 5000);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@ -343,35 +264,12 @@ const useRealtimeData = (formId, sheetName, direction, formType, year) => {
|
|||||||
subscribeToCellEditEnd,
|
subscribeToCellEditEnd,
|
||||||
subscribeToProgramAdds,
|
subscribeToProgramAdds,
|
||||||
subscribeToProjectAdds,
|
subscribeToProjectAdds,
|
||||||
formatedToSubRows,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const updateData = useCallback(
|
|
||||||
(newData) => {
|
|
||||||
if (Array.isArray(newData) && !newData[0]?.subRows) {
|
|
||||||
const maxDepth = newData.reduce(
|
|
||||||
(prev, current) => {
|
|
||||||
return (prev.depth || 0) > (current.depth || 0) ? prev : current;
|
|
||||||
},
|
|
||||||
{ depth: 0 },
|
|
||||||
).depth;
|
|
||||||
|
|
||||||
const formattedData = formatedToSubRows(maxDepth, newData);
|
|
||||||
setData(formattedData);
|
|
||||||
} else {
|
|
||||||
setData(newData);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[formatedToSubRows],
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data,
|
data,
|
||||||
setData,
|
|
||||||
columnsCurStage,
|
columnsCurStage,
|
||||||
isConnected,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
error,
|
|
||||||
editingCells,
|
editingCells,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,32 +1,49 @@
|
|||||||
import { useCallback, useMemo } from 'react';
|
import { useCallback, useMemo, useRef } from 'react';
|
||||||
import { validationRules } from '../constants/validation';
|
import { validationRules } from '../constants/validation';
|
||||||
import { buildColumnHeaderPaths, collectInvalidErrors, isValidationRuleEnabled } from '../utils/validationUtils';
|
import { buildColumnHeaderPaths, collectInvalidErrors, isValidationRuleEnabled } from '../utils/validationUtils';
|
||||||
|
|
||||||
export const useValidationRules = (data = [], columns = [], formType, sheetName) => {
|
const EMPTY_ARRAY = [];
|
||||||
const headerPaths = useMemo(() => buildColumnHeaderPaths(columns), [columns]);
|
|
||||||
|
export const useValidationRules = (data, columns, formType, sheetName) => {
|
||||||
|
const safeData = data || EMPTY_ARRAY;
|
||||||
|
const safeColumns = columns || EMPTY_ARRAY;
|
||||||
|
const stableErrorsRef = useRef([]);
|
||||||
|
const headerPaths = useMemo(() => buildColumnHeaderPaths(safeColumns), [safeColumns]);
|
||||||
const activeRules = useMemo(
|
const activeRules = useMemo(
|
||||||
() => validationRules.filter((rule) => isValidationRuleEnabled(rule, { formType, sheetName })),
|
() => validationRules.filter((rule) => isValidationRuleEnabled(rule, { formType, sheetName })),
|
||||||
[formType, sheetName],
|
[formType, sheetName],
|
||||||
);
|
);
|
||||||
|
|
||||||
const errors = useMemo(() => {
|
const calculatedErrors = useMemo(() => {
|
||||||
const result = [];
|
const result = [];
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
|
|
||||||
for (const rule of activeRules) {
|
for (const rule of activeRules) {
|
||||||
collectInvalidErrors(data, rule, headerPaths, result, seen);
|
collectInvalidErrors(safeData, rule, headerPaths, result, seen);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}, [activeRules, data, headerPaths]);
|
}, [activeRules, headerPaths, safeData]);
|
||||||
|
|
||||||
|
const previousErrors = stableErrorsRef.current;
|
||||||
|
const errorsAreEqual =
|
||||||
|
previousErrors.length === calculatedErrors.length &&
|
||||||
|
previousErrors.every(
|
||||||
|
(error, index) =>
|
||||||
|
error.id === calculatedErrors[index].id &&
|
||||||
|
error.columnId === calculatedErrors[index].columnId &&
|
||||||
|
error.message === calculatedErrors[index].message,
|
||||||
|
);
|
||||||
|
if (!errorsAreEqual) {
|
||||||
|
stableErrorsRef.current = calculatedErrors;
|
||||||
|
}
|
||||||
|
const errors = stableErrorsRef.current;
|
||||||
|
|
||||||
const isCellInvalid = useCallback(
|
const isCellInvalid = useCallback(
|
||||||
(columnId, value, row) =>
|
(columnId, value, row) =>
|
||||||
activeRules.some(
|
activeRules.some(
|
||||||
(rule) =>
|
(rule) =>
|
||||||
rule.columnKeys.includes(columnId) &&
|
rule.columnKeys.includes(columnId) && (!rule.appliesToRow || rule.appliesToRow(row)) && rule.isInvalid(value, row, columnId),
|
||||||
(!rule.appliesToRow || rule.appliesToRow(row)) &&
|
|
||||||
rule.isInvalid(value, row, columnId),
|
|
||||||
),
|
),
|
||||||
[activeRules],
|
[activeRules],
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,31 +1,19 @@
|
|||||||
import React, { useEffect, useRef, useState, useMemo, useCallback } from 'react';
|
import React, { useEffect, useRef, useState, useMemo, useCallback } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import { useParams } from 'react-router';
|
import { useParams } from 'react-router';
|
||||||
import { useRealtime } from './contexts/RealtimeContext';
|
import { useVspOptions } from './contexts/RealtimeContext';
|
||||||
|
|
||||||
import { sectionCodeColor } from './constants/columnConfig';
|
|
||||||
import { blueColumn, greenColumn } from './constants/columnColors';
|
|
||||||
import { ROLES_NAME_ID } from '../../constants/constants';
|
import { ROLES_NAME_ID } from '../../constants/constants';
|
||||||
|
import { blueColumn } from './constants/columnColors';
|
||||||
|
import { sectionCodeColor } from './constants/columnConfig';
|
||||||
|
|
||||||
import VspDropdownEditCell from './Cell/EditCell/VspDropdownEditCell';
|
import VspDropdownEditCell from './Cell/EditCell/VspDropdownEditCell';
|
||||||
|
|
||||||
const EditCellPortal = React.memo(({
|
const EditCellPortal = React.memo(({ cell, table, EditCell, onError, isEditable }) => {
|
||||||
cell,
|
|
||||||
table,
|
|
||||||
EditCell,
|
|
||||||
onSaveStart,
|
|
||||||
onSaveEnd,
|
|
||||||
onError,
|
|
||||||
isEditable
|
|
||||||
}) => {
|
|
||||||
const { formId, formType, sheetName, direction } = useParams();
|
const { formId, formType, sheetName, direction } = useParams();
|
||||||
const tableKey = `${formId}_${formType}_${sheetName}_${direction}`;
|
const tableKey = `${formId}_${formType}_${sheetName}_${direction}`;
|
||||||
const ref = useRef(null);
|
const ref = useRef(null);
|
||||||
const [refTbody, setRefTbody] = useState(null);
|
const [refTbody, setRefTbody] = useState(null);
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
|
||||||
|
|
||||||
const { endEditing: contextEndEditing } = useRealtime();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (ref.current) {
|
if (ref.current) {
|
||||||
const tbodyRef = ref.current.offsetParent?.offsetParent?.offsetParent;
|
const tbodyRef = ref.current.offsetParent?.offsetParent?.offsetParent;
|
||||||
@ -35,54 +23,50 @@ const EditCellPortal = React.memo(({
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleChange = useCallback((val) => {
|
const handleChange = useCallback(
|
||||||
table.setEditingCell(null);
|
(val) => {
|
||||||
try {
|
table.setEditingCell(null);
|
||||||
if (table.options.meta?.updateCell) {
|
try {
|
||||||
const success = table.options.meta.updateCell(
|
if (table.options.meta?.updateCell) {
|
||||||
cell.row,
|
const success = table.options.meta.updateCell(cell.row, cell.column, val);
|
||||||
cell.column,
|
if (!success) {
|
||||||
val
|
console.error('Failed to update cell via WebSocket');
|
||||||
);
|
onError?.('Не удалось сохранить изменение');
|
||||||
if (!success) {
|
}
|
||||||
console.error('Failed to update cell via WebSocket');
|
|
||||||
onError?.('Не удалось сохранить изменение');
|
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating cell:', error);
|
||||||
|
onError?.(error.message);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
},
|
||||||
console.error('Error updating cell:', error);
|
[table, cell, onError],
|
||||||
onError?.(error.message);
|
);
|
||||||
}
|
|
||||||
}, [table, cell, onError]);
|
|
||||||
|
|
||||||
const editCellProps = useMemo(() => ({
|
const editCellProps = useMemo(
|
||||||
refCell: ref,
|
() => ({
|
||||||
cell,
|
refCell: ref,
|
||||||
value: cell.getValue(),
|
cell,
|
||||||
disabled: !isEditable,
|
value: cell.getValue(),
|
||||||
onChange: handleChange,
|
disabled: !isEditable,
|
||||||
tableId: tableKey,
|
onChange: handleChange,
|
||||||
table,
|
tableId: tableKey,
|
||||||
cellId: `${cell.row.id}_${cell.column.id}`,
|
table,
|
||||||
}), [cell, isEditable, handleChange, tableKey, table]);
|
cellId: `${cell.row.id}_${cell.column.id}`,
|
||||||
|
}),
|
||||||
|
[cell, isEditable, handleChange, tableKey, table],
|
||||||
|
);
|
||||||
|
|
||||||
const editType = cell.column.columnDef?.editType;
|
const editType = cell.column.columnDef?.editType;
|
||||||
|
|
||||||
const portalContent = useMemo(() => {
|
const portalContent = useMemo(() => {
|
||||||
if (!refTbody || isSaving) return null;
|
if (!refTbody) return null;
|
||||||
|
|
||||||
if (editType === 'vsp_dropdown') {
|
if (editType === 'vsp_dropdown') {
|
||||||
return createPortal(
|
return createPortal(<VspDropdownEditCell {...editCellProps} />, refTbody);
|
||||||
<VspDropdownEditCell {...editCellProps} />,
|
|
||||||
refTbody
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return createPortal(
|
return createPortal(<EditCell {...editCellProps} />, refTbody);
|
||||||
<EditCell {...editCellProps} />,
|
}, [refTbody, editCellProps, EditCell, editType]);
|
||||||
refTbody
|
|
||||||
);
|
|
||||||
}, [refTbody, isSaving, editCellProps, EditCell, editType]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@ -94,8 +78,7 @@ const EditCellPortal = React.memo(({
|
|||||||
|
|
||||||
function getColorCell(colors, column, row) {
|
function getColorCell(colors, column, row) {
|
||||||
const rowType = row?.original?.row_type || row?.row_type;
|
const rowType = row?.original?.row_type || row?.row_type;
|
||||||
const sectionCodeValue =
|
const sectionCodeValue = row?.original?.data?.section_code ?? row?.original?.data?.header?.section_code;
|
||||||
row?.original?.data?.section_code ?? row?.original?.data?.header?.section_code;
|
|
||||||
|
|
||||||
if (sectionCodeValue !== null && sectionCodeValue !== undefined && sectionCodeValue !== '') {
|
if (sectionCodeValue !== null && sectionCodeValue !== undefined && sectionCodeValue !== '') {
|
||||||
const sectionCode = String(sectionCodeValue)[0];
|
const sectionCode = String(sectionCodeValue)[0];
|
||||||
@ -105,8 +88,7 @@ function getColorCell(colors, column, row) {
|
|||||||
return colors[column.id]?.color_type?.[rowType];
|
return colors[column.id]?.color_type?.[rowType];
|
||||||
}
|
}
|
||||||
|
|
||||||
const UPPERCASE_MONTH_PATTERN =
|
const UPPERCASE_MONTH_PATTERN = /ЯНВАРЬ|ФЕВРАЛЬ|МАРТ|АПРЕЛЬ|МАЙ|ИЮНЬ|ИЮЛЬ|АВГУСТ|СЕНТЯБРЬ|ОКТЯБРЬ|НОЯБРЬ|ДЕКАБРЬ/g;
|
||||||
/ЯНВАРЬ|ФЕВРАЛЬ|МАРТ|АПРЕЛЬ|МАЙ|ИЮНЬ|ИЮЛЬ|АВГУСТ|СЕНТЯБРЬ|ОКТЯБРЬ|НОЯБРЬ|ДЕКАБРЬ/g;
|
|
||||||
|
|
||||||
const normalizeMonthHeader = (header) => {
|
const normalizeMonthHeader = (header) => {
|
||||||
if (typeof header !== 'string') return header;
|
if (typeof header !== 'string') return header;
|
||||||
@ -119,12 +101,17 @@ const normalizeMonthHeader = (header) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const CellWithVspOptions = React.memo(({ CellComponent, cellProps }) => {
|
||||||
|
const vspOptions = useVspOptions();
|
||||||
|
return <CellComponent {...cellProps} vspOptions={vspOptions} />;
|
||||||
|
});
|
||||||
|
|
||||||
export const getTableColumns = ({
|
export const getTableColumns = ({
|
||||||
Cell,
|
Cell,
|
||||||
EditCell,
|
EditCell,
|
||||||
columnsConfig,
|
columnsConfig,
|
||||||
columnsCurStage,
|
columnsCurStage,
|
||||||
user,
|
userRoleId,
|
||||||
onCellUpdateError,
|
onCellUpdateError,
|
||||||
onCellNumberClick,
|
onCellNumberClick,
|
||||||
isCellInvalid,
|
isCellInvalid,
|
||||||
@ -137,11 +124,11 @@ export const getTableColumns = ({
|
|||||||
|
|
||||||
const isEditable = (row, column) => {
|
const isEditable = (row, column) => {
|
||||||
if (row.original?.row_type !== 'INPUT') return false;
|
if (row.original?.row_type !== 'INPUT') return false;
|
||||||
if (user.role_id === ROLES_NAME_ID.admin) return true;
|
if (userRoleId === ROLES_NAME_ID.admin) return true;
|
||||||
const keyCol = column.id;
|
const keyCol = column.id;
|
||||||
if (columnsCurStage.includes(keyCol)) return true;
|
if (columnsCurStage.includes(keyCol)) return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
};
|
||||||
|
|
||||||
const getCachedCellProps = (row, column, table) => {
|
const getCachedCellProps = (row, column, table) => {
|
||||||
const key = `${row.id}_${column.id}`;
|
const key = `${row.id}_${column.id}`;
|
||||||
@ -149,8 +136,6 @@ export const getTableColumns = ({
|
|||||||
const isInvalid = isCellInvalid?.(column.id, value, row.original) || false;
|
const isInvalid = isCellInvalid?.(column.id, value, row.original) || false;
|
||||||
const isEditableCell = isEditable(row, column);
|
const isEditableCell = isEditable(row, column);
|
||||||
const backgroundColor = getColorCell(columnColors, column, row);
|
const backgroundColor = getColorCell(columnColors, column, row);
|
||||||
const isUpdating = table.options.meta?.updatingCells?.[key];
|
|
||||||
|
|
||||||
if (!cellPropsCache.has(row)) {
|
if (!cellPropsCache.has(row)) {
|
||||||
cellPropsCache.set(row, {});
|
cellPropsCache.set(row, {});
|
||||||
}
|
}
|
||||||
@ -159,19 +144,21 @@ export const getTableColumns = ({
|
|||||||
if (rowCache[key]) {
|
if (rowCache[key]) {
|
||||||
const cached = rowCache[key];
|
const cached = rowCache[key];
|
||||||
const currentGlobalFilter = table.getState().globalFilter;
|
const currentGlobalFilter = table.getState().globalFilter;
|
||||||
const currentColumnFilter = table.getState().columnFilters?.find(f => f.id === column.id)?.value;
|
const currentColumnFilter = table.getState().columnFilters?.find((f) => f.id === column.id)?.value;
|
||||||
|
|
||||||
if (cached.globalFilter === currentGlobalFilter &&
|
if (
|
||||||
cached.columnFilter === currentColumnFilter &&
|
cached.globalFilter === currentGlobalFilter &&
|
||||||
cached.value === value &&
|
cached.columnFilter === currentColumnFilter &&
|
||||||
cached.isInvalid === isInvalid &&
|
cached.value === value &&
|
||||||
cached.backgroundColor === backgroundColor) {
|
cached.isInvalid === isInvalid &&
|
||||||
return cached;
|
cached.backgroundColor === backgroundColor
|
||||||
}
|
) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const globalFilter = table.getState().globalFilter;
|
const globalFilter = table.getState().globalFilter;
|
||||||
const columnFilter = table.getState().columnFilters?.find(f => f.id === column.id)?.value;
|
const columnFilter = table.getState().columnFilters?.find((f) => f.id === column.id)?.value;
|
||||||
|
|
||||||
const props = {
|
const props = {
|
||||||
globalFilter,
|
globalFilter,
|
||||||
@ -187,7 +174,7 @@ export const getTableColumns = ({
|
|||||||
return props;
|
return props;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getCachedEditProps = (row, column, table) => {
|
const getCachedEditProps = (row, column) => {
|
||||||
const key = `${row.id}_${column.id}`;
|
const key = `${row.id}_${column.id}`;
|
||||||
|
|
||||||
if (!editPropsCache.has(row)) {
|
if (!editPropsCache.has(row)) {
|
||||||
@ -211,34 +198,31 @@ export const getTableColumns = ({
|
|||||||
const processColumns = (columns) => {
|
const processColumns = (columns) => {
|
||||||
for (const col of columns) {
|
for (const col of columns) {
|
||||||
col.header = normalizeMonthHeader(col.header);
|
col.header = normalizeMonthHeader(col.header);
|
||||||
|
const usesVspOptions = col.editType === 'vsp_dropdown';
|
||||||
|
|
||||||
col.Cell = ({ cell, table, column, row }) => {
|
col.Cell = ({ cell, table, column, row }) => {
|
||||||
const { vspOptions } = useRealtime();
|
|
||||||
const props = getCachedCellProps(row, column, table);
|
const props = getCachedCellProps(row, column, table);
|
||||||
|
|
||||||
const cellProps = useMemo(() => ({
|
const cellProps = useMemo(
|
||||||
row,
|
() => ({
|
||||||
column,
|
row,
|
||||||
cell,
|
column,
|
||||||
vspOptions,
|
cell,
|
||||||
...props,
|
...props,
|
||||||
}), [row, column, cell, props, vspOptions,]);
|
}),
|
||||||
|
[row, column, cell, props],
|
||||||
|
);
|
||||||
|
|
||||||
return <Cell {...cellProps} />;
|
return usesVspOptions ? <CellWithVspOptions CellComponent={Cell} cellProps={cellProps} /> : <Cell {...cellProps} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
col.Edit = ({ cell, table, row, column }) => {
|
col.Edit = ({ cell, table, row, column }) => {
|
||||||
const props = getCachedEditProps(row, column, table);
|
const props = getCachedEditProps(row, column);
|
||||||
|
|
||||||
const editComponent = useMemo(() => (
|
const editComponent = useMemo(
|
||||||
<EditCellPortal
|
() => <EditCellPortal cell={cell} table={table} EditCell={EditCell} onError={onCellUpdateError} isEditable={props.isEditable} />,
|
||||||
cell={cell}
|
[cell, table, EditCell, onCellUpdateError, props.isEditable],
|
||||||
table={table}
|
);
|
||||||
EditCell={EditCell}
|
|
||||||
onError={onCellUpdateError}
|
|
||||||
isEditable={props.isEditable}
|
|
||||||
/>
|
|
||||||
), [cell, table, EditCell, onCellUpdateError, props.isEditable]);
|
|
||||||
|
|
||||||
return editComponent;
|
return editComponent;
|
||||||
};
|
};
|
||||||
@ -251,8 +235,7 @@ export const getTableColumns = ({
|
|||||||
processColumns(col.columns);
|
processColumns(col.columns);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
processColumns(columns);
|
processColumns(columns);
|
||||||
|
|
||||||
@ -265,7 +248,7 @@ export const getTableColumns = ({
|
|||||||
const handleClick = useCallback(() => {
|
const handleClick = useCallback(() => {
|
||||||
onCellNumberClick(row.id);
|
onCellNumberClick(row.id);
|
||||||
}, [row.id, onCellNumberClick]);
|
}, [row.id, onCellNumberClick]);
|
||||||
return <button type="button" onClick={handleClick}>{`${cell.getValue()} `}</button>;
|
return <button type='button' onClick={handleClick}>{`${cell.getValue()} `}</button>;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -2,35 +2,38 @@ import { ArrowDropDown, ChevronRight, ExpandMore } from '@mui/icons-material';
|
|||||||
import { CheckBox, CheckBoxOutlineBlank, IndeterminateCheckBox } from '@mui/icons-material';
|
import { CheckBox, CheckBoxOutlineBlank, IndeterminateCheckBox } from '@mui/icons-material';
|
||||||
import { Box, Checkbox, InputAdornment, Popover, TextField, Typography } from '@mui/material';
|
import { Box, Checkbox, InputAdornment, Popover, TextField, Typography } from '@mui/material';
|
||||||
import { SimpleTreeView, TreeItem } from '@mui/x-tree-view';
|
import { SimpleTreeView, TreeItem } from '@mui/x-tree-view';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { memo, useMemo, useState } from 'react';
|
||||||
import { filterColumnTree, getColumnTreeLeafKeys } from '../RealtimeTable/utils/columnUtils';
|
import { filterColumnTree, getColumnTreeLeafKeys } from '../RealtimeTable/utils/columnUtils';
|
||||||
|
|
||||||
|
const EMPTY_IDS = [];
|
||||||
|
|
||||||
const CollapsibleTree = ({
|
const CollapsibleTree = ({
|
||||||
columnTree,
|
columnTree,
|
||||||
excludeColumnKeys = [],
|
excludeColumnKeys = EMPTY_IDS,
|
||||||
placeholder = 'Скрыть столбцы',
|
placeholder = 'Скрыть столбцы',
|
||||||
placeholderSelect = 'Скрыто столбцов: ',
|
placeholderSelect = 'Скрыто столбцов: ',
|
||||||
selectedIds = [],
|
selectedIds = EMPTY_IDS,
|
||||||
onSelectNode,
|
onSelectNode,
|
||||||
|
onSelectAllNodes,
|
||||||
forStage = false,
|
forStage = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [expandedItems, setExpandedItems] = useState([]);
|
const [expandedItems, setExpandedItems] = useState([]);
|
||||||
const [anchorEl, setAnchorEl] = useState(null);
|
const [anchorEl, setAnchorEl] = useState(null);
|
||||||
const [selectedNodes, setSelectedNodes] = useState([]);
|
const selectedNodes = selectedIds;
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setSelectedNodes(selectedIds);
|
|
||||||
}, [selectedIds]);
|
|
||||||
|
|
||||||
const visibleColumnTree = useMemo(() => filterColumnTree(columnTree, excludeColumnKeys), [columnTree, excludeColumnKeys]);
|
const visibleColumnTree = useMemo(() => filterColumnTree(columnTree, excludeColumnKeys), [columnTree, excludeColumnKeys]);
|
||||||
|
|
||||||
const visibleLeafKeys = useMemo(() => getColumnTreeLeafKeys(visibleColumnTree), [visibleColumnTree]);
|
const visibleLeafKeys = useMemo(() => getColumnTreeLeafKeys(visibleColumnTree), [visibleColumnTree]);
|
||||||
|
|
||||||
const handleExpandedItemsChange = (event, itemIds) => {
|
const handleExpandedItemsChange = (_event, itemIds) => {
|
||||||
setExpandedItems(itemIds);
|
setExpandedItems(itemIds);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSelectAll = (isSelected) => {
|
const handleSelectAll = (isSelected) => {
|
||||||
|
if (onSelectAllNodes) {
|
||||||
|
onSelectAllNodes(visibleLeafKeys, !isSelected);
|
||||||
|
return;
|
||||||
|
}
|
||||||
for (const col of visibleColumnTree) {
|
for (const col of visibleColumnTree) {
|
||||||
onSelectNode?.(col, !isSelected);
|
onSelectNode?.(col, !isSelected);
|
||||||
}
|
}
|
||||||
@ -248,4 +251,4 @@ const CollapsibleTree = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default CollapsibleTree;
|
export default memo(CollapsibleTree);
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { InputAdornment, TextField } from '@mui/material';
|
import { InputAdornment, TextField } from '@mui/material';
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { memo, useEffect, useRef, useState } from 'react';
|
||||||
import { Search } from './icons/icons';
|
import { Search } from './icons/icons';
|
||||||
|
|
||||||
function SearchComponent({ placeholder = 'Поиск...', value = '', onChange, debounceMs = 0, height = '2rem', sx: sxProp, ...rest }) {
|
function SearchComponent({ placeholder = 'Поиск...', value = '', onChange, debounceMs = 0, height = '2rem', sx: sxProp, ...rest }) {
|
||||||
@ -75,4 +75,4 @@ function SearchComponent({ placeholder = 'Поиск...', value = '', onChange,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default SearchComponent;
|
export default memo(SearchComponent);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user