Compare commits

..

No commits in common. "e6133b82fe5a6a918ed8c37d2dd2ecc10ac3050a" and "9f652e5b94c475b1c126f6b4f56f024cbbc8673b" have entirely different histories.

4 changed files with 419 additions and 503 deletions

View File

@ -1,67 +1,41 @@
import React, { memo, useMemo, useCallback } from 'react'; import React, { useEffect, useState } from 'react';
import { useMemo } from 'react';
import styled from '@emotion/styled';
import { useRealtime } from '../../contexts/RealtimeContext'; import { useRealtime } from '../../contexts/RealtimeContext';
import { toast } from 'react-toastify';
// Константы вне компонента const ContainerForText = styled.span`
const BASE_CELL_STYLES = { display: -webkit-box;
width: '100%', -webkit-box-orient: vertical;
height: '100%', -webkit-line-clamp: 3;
display: 'flex', overflow: hidden;
alignItems: 'center', white-space: pre-wrap;
justifyContent: 'center', `;
boxSizing: 'border-box',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
border: '2px solid transparent',
padding: '8px',
};
const LOCKED_STYLES = { // Стилизованный компонент для плашки блокировки
border: '2px solid #e0e0e0', const LockBadge = styled.div`
backgroundColor: '#f5f5f5', position: absolute;
cursor: 'not-allowed', top: 2px;
opacity: 0.85, right: 2px;
}; background: rgba(0, 0, 0, 0.7);
color: white;
const LOCK_BADGE_STYLES = { font-size: 9px;
position: 'absolute', padding: 1px 4px;
top: '2px', border-radius: 3px;
right: '2px', pointer-events: none;
background: 'rgba(0, 0, 0, 0.7)', z-index: 10;
color: 'white', font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
fontSize: '9px', letter-spacing: 0.3px;
padding: '1px 4px', backdrop-filter: blur(4px);
borderRadius: '3px', border: 1px solid rgba(255, 255, 255, 0.1);
pointerEvents: 'none', `;
zIndex: 10,
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
letterSpacing: '0.3px',
backdropFilter: 'blur(4px)',
border: '1px solid rgba(255, 255, 255, 0.1)',
};
const CONTAINER_STYLES = {
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 3,
overflow: 'hidden',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
};
const INTEGER_COLUMN_IDS = new Set([
'data.header.num_group',
'data.nomenclature_group_id',
'data.header.item_id',
'data.article_id',
'data.code_razdela',
]);
// Функция для определения яркости цвета
const getColorBrightness = (hexColor) => { const getColorBrightness = (hexColor) => {
if (!hexColor) return 255; if (!hexColor) return 255;
const color = hexColor.replace('#', ''); const color = hexColor.replace('#', '');
let r, g, b; let r, g, b;
if (color.length === 3) { if (color.length === 3) {
r = parseInt(color[0] + color[0], 16); r = parseInt(color[0] + color[0], 16);
@ -74,132 +48,174 @@ const getColorBrightness = (hexColor) => {
} else { } else {
return 255; return 255;
} }
return (0.299 * r + 0.587 * g + 0.114 * b); return (0.299 * r + 0.587 * g + 0.114 * b);
}; };
const formatNumber = (value, asInteger = false) => { // Функция для подсветки текста
if (value === null || value === undefined || value === '') return String(value || ''); const highlightText = (text, searchQueries) => {
const num = Number(value); if (!text) return text;
if (isNaN(num)) return String(value); const cleanSearchQueries = searchQueries.filter(q => (q !== undefined && q !== ''));
return num.toLocaleString('ru-RU', { if (cleanSearchQueries.length == 0) return text;
minimumFractionDigits: asInteger ? 0 : 1,
maximumFractionDigits: asInteger ? 0 : 1, const escapedQueries = cleanSearchQueries.map(query => query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
useGrouping: true, const regex = new RegExp(`(${escapedQueries.join('|')})`, 'gi');
}); const parts = text.split(regex);
return parts.map((part, index) =>
regex.test(part) ? (
<mark
key={index}
style={{
backgroundColor: '#ffeb3b',
color: '#000',
fontWeight: 'bold',
padding: '0 2px',
borderRadius: '2px',
}}
>
{part}
</mark>
) : (
part
),
);
}; };
// Оптимизированная функция подсветки const highlightWithFormatting = (originalValue, formattedValue, searchQueries) => {
const createHighlightedContent = (originalValue, displayValue, searchQueries) => { if (!originalValue && originalValue !== 0) return formattedValue;
const cleanQueries = searchQueries.filter(Boolean);
if (cleanQueries.length === 0) return displayValue;
const searchStr = String(originalValue ?? displayValue); const cleanSearchQueries = searchQueries.filter(q => (q !== undefined && q !== ''));
const escapedQueries = cleanQueries.map(q => q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); if (cleanSearchQueries.length == 0) return formattedValue;
const originalString = String(originalValue);
const escapedQueries = cleanSearchQueries.map(query => query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
const regex = new RegExp(`(${escapedQueries.join('|')})`, 'gi'); const regex = new RegExp(`(${escapedQueries.join('|')})`, 'gi');
if (!regex.test(searchStr)) return displayValue; if (!regex.test(originalString)) {
return formattedValue;
}
const parts = searchStr.split(regex); return (
return parts.map((part, index) => { <mark
if (!regex.test(part)) return part; style={{
return React.createElement('mark', {
key: index,
style: {
backgroundColor: '#ffeb3b', backgroundColor: '#ffeb3b',
color: '#000', color: '#000',
fontWeight: 'bold', fontWeight: 'bold',
padding: '0 2px', padding: '0 2px',
borderRadius: '2px', borderRadius: '2px',
}, }}
}, part); >
{formattedValue}
</mark>
);
};
const INTEGER_COLUMN_IDS = new Set([
'data.header.num_group',
'data.nomenclature_group_id',
'data.header.item_id',
'data.article_id',
'data.code_razdela',
]);
// Функция для форматирования числа в финансовый формат
const formatNumber = (value, asInteger = false) => {
if (value === null || value === undefined || value === '') return String(value || '');
const num = Number(value);
if (isNaN(num)) return String(value);
if (asInteger) {
return num.toLocaleString('ru-RU', {
minimumFractionDigits: 0,
maximumFractionDigits: 0,
useGrouping: true,
});
}
return num.toLocaleString('ru-RU', {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
useGrouping: true,
}); });
}; };
const CellComponent = ({ const Cell = React.memo(({ cell, row, column, onClick, globalFilter, columnFilter, backgroundColor, color, isEditable }) => {
cell,
row,
column,
onClick,
globalFilter,
columnFilter,
backgroundColor,
color,
isEditable,
isUpdating,
onCellNumberClick,
}) => {
const { lockedCells } = useRealtime(); const { lockedCells } = useRealtime();
const cellKey = `${row.id}_${column.id}`; const cellKey = `${row.id}_${column.id}`;
const isLocked = lockedCells.includes(cellKey); const isLocked = lockedCells.includes(cellKey);
// Мемоизация значения const cellValue = cell.getValue();
const { rawValue, displayValue, isNumeric } = useMemo(() => { let originalValue = cellValue;
const value = cell.getValue(); let displayValue = String(cellValue || '');
const isNum = !isNaN(Number(value)) && value !== null && value !== undefined && value !== '';
let display = String(value || '');
if (isNum) { const isNumeric = !isNaN(Number(cellValue)) && cellValue !== null && cellValue !== undefined && cellValue !== '';
const asInteger = INTEGER_COLUMN_IDS.has(column.id); if (isNumeric) {
display = formatNumber(value, asInteger); const asInteger = INTEGER_COLUMN_IDS.has(column.id);
} displayValue = formatNumber(cellValue, asInteger);
}
return { rawValue: value, displayValue: display, isNumeric: isNum };
}, [cell, column.id]);
const highlightedContent = useMemo(() => { const highlightedContent = useMemo(() => {
const searchQueries = [globalFilter, columnFilter]; if (!isNumeric) {
return createHighlightedContent(rawValue, displayValue, searchQueries); return highlightText(displayValue, [globalFilter, columnFilter]);
}, [rawValue, displayValue, globalFilter, columnFilter]);
const textColor = useMemo(() => {
if (isLocked) return '#999999';
const brightness = getColorBrightness(backgroundColor);
return brightness < 128 ? '#ffffff' : '#000000';
}, [backgroundColor, isLocked]);
const cellStyles = useMemo(() => ({
...BASE_CELL_STYLES,
backgroundColor: isLocked ? '#f5f5f5' : backgroundColor,
color: textColor,
...(isLocked ? LOCKED_STYLES : {}),
}), [backgroundColor, isLocked, textColor]);
const lockBadge = useMemo(() => {
if (!isLocked) return null;
return <div style={LOCK_BADGE_STYLES}>🔒</div>;
}, [isLocked]);
const handleClick = useCallback(() => {
if (!isLocked && onClick) {
onClick();
} }
}, [isLocked, onClick]); return highlightWithFormatting(originalValue, displayValue, [globalFilter, columnFilter]);
}, [originalValue, displayValue, globalFilter, columnFilter, isNumeric]);
// Определяем цвет текста на основе яркости фона
const getTextColor = () => {
const brightness = getColorBrightness(backgroundColor);
// Если яркость меньше 128 (темный фон) - используем белый текст, иначе черный
return brightness < 128 ? '#ffffff' : '#000000';
};
// Базовые стили для заблокированной ячейки
const lockedStyles = isLocked ? {
border: '2px solid #e0e0e0',
backgroundColor: '#f5f5f5',
cursor: 'not-allowed',
opacity: 0.85,
} : {};
// Определяем финальный цвет текста
const finalTextColor = isLocked ? '#999999' : getTextColor();
return ( return (
<div <div
className="cell" className="cell"
style={cellStyles} style={{
onClick={handleClick} width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
boxSizing: 'border-box',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
border: '2px solid transparent',
padding: '8px',
backgroundColor: isLocked ? '#f5f5f5' : backgroundColor,
color: finalTextColor,
...lockedStyles,
}}
onClick={isLocked ? undefined : onClick}
> >
<span style={CONTAINER_STYLES}>{highlightedContent}</span> <ContainerForText>{highlightedContent}</ContainerForText>
{lockBadge} {isLocked && (
<LockBadge>
🔒
</LockBadge>
)}
</div> </div>
); );
};
const Cell = React.memo(CellComponent, (prevProps, nextProps) => {
// Возвращаем true если пропсы равны (не нужно перерендеривать)
return (
prevProps.cell.getValue() === nextProps.cell.getValue() &&
prevProps.row.id === nextProps.row.id &&
prevProps.column.id === nextProps.column.id &&
prevProps.globalFilter === nextProps.globalFilter &&
prevProps.columnFilter === nextProps.columnFilter &&
prevProps.backgroundColor === nextProps.backgroundColor &&
prevProps.isEditable === nextProps.isEditable &&
prevProps.isUpdating === nextProps.isUpdating &&
prevProps.onCellNumberClick === nextProps.onCellNumberClick
);
}); });
export default Cell; export default Cell;

View File

@ -1,228 +1,195 @@
import React, { memo, useEffect, useRef, useLayoutEffect, useState, useCallback, useMemo } from 'react'; // EditCell.js - обновленная версия
import { useEffect, useRef, useLayoutEffect, useState } from 'react';
import { isFormula, extractFormula, calculateFormula, formatNumber } from '../../utils/formulaUtils'; import { isFormula, extractFormula, calculateFormula, formatNumber } from '../../utils/formulaUtils';
import { saveToStorage, loadFromStorage } from '../../utils/localStorageUtils'; import { saveToStorage, loadFromStorage } from '../../utils/localStorageUtils';
import { useRealtime } from '../../contexts/RealtimeContext'; import { useRealtime } from '../../contexts/RealtimeContext';
const EDITOR_STYLES = { const EditCell = ({ refCell, onChange, disabled, value, tableId, cellId, table }) => {
position: 'absolute',
zIndex: 12,
top: 0,
};
const FORMULA_INDICATOR_STYLES = {
position: 'absolute',
top: '-20px',
left: '4px',
fontSize: '10px',
color: '#666',
background: '#f0f0f0',
padding: '2px 6px',
borderRadius: '3px',
pointerEvents: 'none',
};
const TEXTAREA_STYLES = {
width: '100%',
height: 'auto',
fieldSizing: 'content',
fontSize: 'inherit',
};
const EditCell = memo(({ refCell, onChange, disabled, value, tableId, cellId, table }) => {
const { endEditing: contextEndEditing } = useRealtime(); const { endEditing: contextEndEditing } = useRealtime();
const [curValue, setCurValue] = useState(value);
const [displayValue, setDisplayValue] = useState(value);
const [isFormulaMode, setIsFormulaMode] = useState(false);
// Ключ для хранения формул в localStorage
const storageKey = `formula_${tableId}_${cellId}`; const storageKey = `formula_${tableId}_${cellId}`;
// Объединенное состояние const trFrag = refCell.current.offsetParent.offsetParent;
const [state, setState] = useState(() => ({ const tdFrag = refCell.current.offsetParent;
currentValue: value, const left = tdFrag.offsetLeft;
displayValue: value, const width = refCell.current.offsetParent.offsetWidth;
isFormulaMode: false, const translateY = trFrag.style.transform;
}));
// Позиция ячейки // Загружаем сохраненную формулу при монтировании
const [position, setPosition] = useState({ left: 0, width: 0, translateY: '' });
const textareaRef = useRef(null);
const refFinished = useRef(false);
// Загрузка сохраненной формулы
useEffect(() => { useEffect(() => {
const savedFormula = loadFromStorage(storageKey); const savedFormula = loadFromStorage(storageKey);
if (savedFormula && isFormula(savedFormula)) { if (savedFormula && isFormula(savedFormula)) {
setIsFormulaMode(true);
setCurValue(savedFormula);
// Вычисляем и отображаем результат
try { try {
const formula = extractFormula(savedFormula); const formula = extractFormula(savedFormula);
const result = calculateFormula(formula); const result = calculateFormula(formula);
setState({ setDisplayValue(formatNumber(result));
currentValue: savedFormula, } catch (error) {
displayValue: formatNumber(result), setDisplayValue('#ОШИБКА');
isFormulaMode: true,
});
} catch {
setState({
currentValue: savedFormula,
displayValue: '#ОШИБКА',
isFormulaMode: true,
});
} }
} else {
setDisplayValue(value);
} }
}, [storageKey]); }, [storageKey, value]);
// Вычисление позиции function useAutoResize(value) {
useLayoutEffect(() => { const ref = useRef(null);
if (!refCell?.current) return;
const td = refCell.current.offsetParent; useLayoutEffect(() => {
const tr = td?.offsetParent; const el = ref.current;
if (!el) return;
if (td && tr) {
setPosition({
left: td.offsetLeft,
width: td.offsetWidth,
translateY: tr.style.transform || '',
});
}
}, [refCell]);
// Auto-resize
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
const resize = () => {
el.style.height = 'auto'; el.style.height = 'auto';
el.style.minHeight = '3rem'; el.style.minHeight = '3rem';
el.style.height = el.scrollHeight + 'px'; el.style.height = el.scrollHeight + 'px';
el.style.maxHeight = '180px'; el.style.maxHeight = '180px';
}; }, [value]);
resize(); return ref;
const observer = new ResizeObserver(resize); }
observer.observe(el);
return () => observer.disconnect(); const ref = useAutoResize(value);
}, [state.currentValue]);
// Фокус при монтировании
useEffect(() => { useEffect(() => {
const el = textareaRef.current; if (ref.current && !disabled) {
if (el && !disabled) { ref.current.focus();
el.focus(); ref.current.setSelectionRange(
el.setSelectionRange(el.value.length, el.value.length); ref.current.value.length,
ref.current.value.length,
);
} }
}, [disabled]); }, [disabled, ref]);
// Сохранение const handleSave = () => {
const handleSave = useCallback(() => { // Проверяем, является ли введенное значение формулой
const { currentValue } = state; if (isFormula(curValue)) {
// Сохраняем формулу в localStorage
if (isFormula(currentValue)) { saveToStorage(storageKey, curValue);
saveToStorage(storageKey, currentValue); // Вычисляем и сохраняем результат
try { try {
const formula = extractFormula(currentValue); const formula = extractFormula(curValue);
const result = calculateFormula(formula); const result = calculateFormula(formula);
const formattedResult = formatNumber(result); const formattedResult = formatNumber(result);
setState(prev => ({ setDisplayValue(formattedResult);
...prev,
displayValue: formattedResult,
isFormulaMode: true,
}));
onChange?.(formattedResult); onChange?.(formattedResult);
} catch { setIsFormulaMode(true);
setState(prev => ({ return;
...prev, } catch (error) {
displayValue: '#ОШИБКА', setDisplayValue('#ОШИБКА');
isFormulaMode: true, onChange?.(curValue); // Сохраняем как текст, если ошибка
})); return;
onChange?.(currentValue);
} }
} else { } else {
// Если это не формула, удаляем сохраненную формулу
localStorage.removeItem(storageKey); localStorage.removeItem(storageKey);
setState(prev => ({ setIsFormulaMode(false);
...prev, setDisplayValue(curValue);
displayValue: currentValue, onChange?.(curValue);
isFormulaMode: false,
}));
onChange?.(currentValue);
} }
}, [state, storageKey, onChange]); };
// Завершение редактирования const handleChangeValue = (event) => {
const finishEditing = useCallback(() => { const input = event.target.value;
if(refFinished.current) return; setCurValue(input);
refFinished.current = true; // При редактировании показываем введенный текст
setDisplayValue(input);
};
// Функция для отображения значения в ячейке
const getDisplayValue = () => {
if (isFormulaMode && isFormula(curValue)) {
return displayValue;
}
return displayValue;
};
const finishEditing = () => {
if (!disabled) { if (!disabled) {
handleSave(); handleSave();
} }
const editingCell = table.getState().editingCell; const editingCell = table.getState().editingCell || null;
if (editingCell) { if (editingCell) {
contextEndEditing?.(editingCell.row, editingCell.column); contextEndEditing?.(editingCell.row, editingCell.column);
} }
}, [disabled, handleSave, table, contextEndEditing]); };
useEffect(() => { useEffect(() => {
const handleClickOutside = (event) => { const handleClickOutside = (event) => {
const el = textareaRef.current; // Проверяем, был ли клик внутри элемента редактирования
if (el && !el.contains(event.target)) { const editElement = ref.current;
if (editElement && !editElement.contains(event.target)) {
finishEditing(); finishEditing();
} }
}; };
document.addEventListener('mousedown', handleClickOutside); document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [finishEditing]);
// Обработчики событий return () => {
const handleChange = useCallback((e) => { document.removeEventListener('mousedown', handleClickOutside);
const value = e.target.value; };
setState(prev => ({ }, [ref, finishEditing]);
...prev,
currentValue: value,
displayValue: value,
}));
}, []);
const handleKeyDown = useCallback((e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
finishEditing();
}
}, [finishEditing]);
// Мемоизация стилей
const editorStyles = useMemo(() => ({
...EDITOR_STYLES,
left: position.left,
width: position.width,
transform: position.translateY,
}), [position]);
const textareaStyles = useMemo(() => ({
...TEXTAREA_STYLES,
backgroundColor: state.isFormulaMode ? '#f8f9fa' : 'white',
border: state.isFormulaMode ? '2px solid #4a90d9' : undefined,
}), [state.isFormulaMode]);
return ( return (
<tr> <tr>
<td> <td>
<div style={editorStyles}> <div
{state.isFormulaMode && ( key="blockForEdit"
<div style={FORMULA_INDICATOR_STYLES}>fx</div> style={{
position: 'absolute',
left: left,
zIndex: 12,
width: width,
transform: translateY,
top: 0,
}}
>
{isFormulaMode && (
<div style={{
position: 'absolute',
top: '-20px',
left: '4px',
fontSize: '10px',
color: '#666',
background: '#f0f0f0',
padding: '2px 6px',
borderRadius: '3px',
pointerEvents: 'none'
}}>
fx
</div>
)} )}
<textarea <textarea
ref={textareaRef} ref={ref}
disabled={disabled} disabled={disabled}
style={textareaStyles} style={{
onChange={handleChange} width: '100%',
value={state.currentValue} height: 'auto',
onKeyDown={handleKeyDown} fieldSizing: 'content',
placeholder={state.isFormulaMode ? 'Введите формулу (начинается с =)' : ''} fontSize: 'inherit',
backgroundColor: isFormulaMode ? '#f8f9fa' : 'white',
border: isFormulaMode ? '2px solid #4a90d9' : undefined,
}}
onChange={handleChangeValue}
value={curValue}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
finishEditing();
}
}}
placeholder={isFormulaMode ? 'Введите формулу (начинается с =)' : ''}
/> />
</div> </div>
</td> </td>
</tr> </tr>
); );
}); };
EditCell.displayName = 'EditCell';
export default EditCell; export default EditCell;

View File

@ -28,7 +28,6 @@ import { CircularProgress } from '@mui/material';
import { additionVspRowTable } from './constants/addingRowConfig'; import { additionVspRowTable } from './constants/addingRowConfig';
import { SelectVspModal } from './Modals/SelectVspModal'; import { SelectVspModal } from './Modals/SelectVspModal';
import { getRowId } from './utils/rowUtils'; import { getRowId } from './utils/rowUtils';
import { debounce } from '@mui/material';
const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => { const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
const { data, setData, isLoading: isTableLoading, editingCells: dataEditingCells } = useRealtimeData(formId, sheetName, direction, formType, year); const { data, setData, isLoading: isTableLoading, editingCells: dataEditingCells } = useRealtimeData(formId, sheetName, direction, formType, year);
@ -48,14 +47,11 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
return additionVspRowTable[formType].includes(sheetName); return additionVspRowTable[formType].includes(sheetName);
}, [formType, sheetName]); }, [formType, sheetName]);
const handleGlobalFilterChange = useCallback( const handleGlobalFilterChange = (value) => {
debounce((value) => { startTransition(() => {
startTransition(() => { setGlobalFilter(value);
setGlobalFilter(value); });
}); };
}, 300),
[]
);
const { const {
isConnected, isConnected,
@ -93,27 +89,17 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
const [columnsConfig, setColumnsConfig] = useState(null); const [columnsConfig, setColumnsConfig] = useState(null);
const configCache = useRef(new Map());
useEffect(() => { useEffect(() => {
if (!formType || !sheetName) return;
const cacheKey = `${formType}_${sheetName}`;
if (configCache.current.has(cacheKey)) {
setColumnsConfig(configCache.current.get(cacheKey));
return;
}
const loadConfig = async () => { const loadConfig = async () => {
try { try {
const { config } = await import(`./constants/${formType}/${sheetName}.js`); const { config } = await import(`./constants/${formType}/${sheetName}.js`);
configCache.current.set(cacheKey, config.config);
setColumnsConfig(config.config); 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: {} }); setColumnsConfig({ columns: [], colors: {} });
} }
}; };
loadConfig(); loadConfig();
}, [formType, sheetName]); }, [formType, sheetName]);
@ -168,7 +154,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
console.error('Error creating columns:', error); console.error('Error creating columns:', error);
return []; return [];
} }
}, [columnsConfig]); }, [columnsConfig, handleUpdateCell, handleClickRowCell, handleCellUpdateError]);
const selectedColumnIdRef = useRef(selectedColumnId); const selectedColumnIdRef = useRef(selectedColumnId);
@ -182,7 +168,7 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
}), [handleUpdateCell]); }), [handleUpdateCell]);
const ROW_VIRTUALIZER_OPTIONS = { const ROW_VIRTUALIZER_OPTIONS = {
overscan: 5, overscan: 30,
scrollPaddingStart: 0, scrollPaddingStart: 0,
scrollPaddingEnd: 0, scrollPaddingEnd: 0,
estimateSize: () => TABLE_ROW_HEIGHT, estimateSize: () => TABLE_ROW_HEIGHT,
@ -320,34 +306,43 @@ const RealtimeTable = ({ formType, formId, sheetName, direction, year }) => {
const table = useMaterialReactTable(tableConfig); const table = useMaterialReactTable(tableConfig);
useEffect(() => { useEffect(() => {
if (!dataEditingCells?.line_id) { if (!dataEditingCells || !dataEditingCells.line_id) {
setEditingCell(null); setEditingCell(null);
return; return;
} }
if (editingCell) return; if (editingCell) return;
const rowId = dataEditingCells.line_id;
// Отложить поиск до следующего тика const columnId = dataEditingCells.column;
requestAnimationFrame(() => { try {
try { const row = table.getRow(rowId);
const row = table.getRow(dataEditingCells.line_id); const column = table.getColumn(columnId);
const cell = row?.getVisibleCells().find( const cell = row?.getVisibleCells().find(c => c.column.id === columnId);
c => c.column.id === dataEditingCells.column if (cell) {
); setEditingCell(cell);
if (cell) setEditingCell(cell);
} catch (error) {
console.error(error);
} }
}); } catch (error) {
}, [dataEditingCells, editingCell, table]); console.error(error);
toast.error('Ошибка редактирования ячейки');
const [isFirstLoad, setIsFirstLoad] = useState(true); }
}, [dataEditingCells, editingCell]);
useEffect(() => { useEffect(() => {
if (isFirstLoad && table && data && columns.length !== 0) { if (table && data && columns.length !== 0) {
setIsFirstLoad(false); setIsLoadingData(true)
setIsLoadingData(true);
} }
}, [data, columns, table, isFirstLoad]); }, [data, columns, table])
useEffect(() => {
// Принудительно обновляем состояние закрепленных колонок
// если так не сделать при скролле будут пропадать закрепленные колонки
if (columnPinning && Object.keys(columnPinning).length > 0) {
const timer = setTimeout(() => {
setColumnPinning(prev => ({ ...prev }));
}, 100);
return () => clearTimeout(timer);
}
}, []);
const handleAddRow = useCallback(() => { const handleAddRow = useCallback(() => {
const allRows = table.getRowModel().rows; const allRows = table.getRowModel().rows;

View File

@ -1,11 +1,11 @@
// getTableColumns.js import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useRef, useState, useMemo, useCallback } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { columns as mockColumns } from '../../mocks/mockTable';
import { config } from './constants/FORM_2/AHR';
import { useParams } from 'react-router'; import { useParams } from 'react-router';
import { useRealtime } from './contexts/RealtimeContext'; import { useRealtime } from './contexts/RealtimeContext';
// Мемоизированный компонент EditCellPortal function EditCellPortal({
const EditCellPortal = React.memo(({
cell, cell,
table, table,
EditCell, EditCell,
@ -13,78 +13,89 @@ const EditCellPortal = React.memo(({
onSaveEnd, onSaveEnd,
onError, onError,
isEditable 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(false);
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
const isDisabled = false;
const { endEditing: contextEndEditing } = useRealtime(); const { endEditing: contextEndEditing } = useRealtime();
// Оптимизация: вычисляем позицию только при монтировании и изменении cell
useEffect(() => { useEffect(() => {
if (ref.current) { if (ref.current) {
const tbodyRef = ref.current.offsetParent?.offsetParent?.offsetParent; const tbodyRef = ref.current.offsetParent?.offsetParent?.offsetParent;
if (tbodyRef && tbodyRef !== refTbody) { setRefTbody(tbodyRef);
setRefTbody(tbodyRef);
}
} }
}, [refTbody]); // Добавляем refTbody в зависимости }, []);
// Мемоизация обработчика изменения const handleChange = async (val) => {
const handleChange = useCallback( (val) => {
table.setEditingCell(null); table.setEditingCell(null);
try { try {
if (table.options.meta?.updateCell) { if (table.options.meta?.updateCell) {
const success = table.options.meta.updateCell( const success = await table.options.meta.updateCell(
cell.row, cell.row,
cell.column, cell.column,
val val
); );
if (!success) { if (success) {
console.log('Cell updated successfully via WebSocket');
} else {
console.error('Failed to update cell via WebSocket'); console.error('Failed to update cell via WebSocket');
onError?.('Не удалось сохранить изменение'); const errorMsg = 'Не удалось сохранить изменение';
onError?.(errorMsg);
} }
} }
} catch (error) { } catch (error) {
console.error('Error updating cell:', error); console.error('Error updating cell:', error);
onError?.(error.message); onError?.(error.message);
} }
}, [table, cell, onError]); };
// Мемоизация пропсов для EditCell
const editCellProps = useMemo(() => ({
refCell: ref,
cell,
value: cell.getValue(),
disabled: !isEditable,
onChange: handleChange,
tableId: tableKey,
table,
cellId: `${cell.row.id}_${cell.column.id}`,
}), [cell, isEditable, handleChange, tableKey, table]);
// Мемоизация портала
const portalContent = useMemo(() => {
if (!refTbody || isSaving) return null;
return createPortal(
<EditCell {...editCellProps} />,
refTbody
);
}, [refTbody, isSaving, editCellProps, EditCell]);
return ( return (
<> <>
<div ref={ref} style={{ width: '100%', height: '100%' }} /> <div
{portalContent} ref={ref}
style={{
width: '100%',
height: '100%',
}}
/>
{refTbody && !isSaving &&
createPortal(
<EditCell
refCell={ref}
cell={cell}
value={cell.getValue()}
disabled={!isEditable}
onChange={handleChange}
tableId={tableKey}
table={table}
cellId={cell.row.id + '_' + cell.column.id}
/>,
refTbody,
)}
{isSaving && (
createPortal(
<div style={{
position: 'absolute',
background: 'rgba(0,0,0,0.5)',
color: 'white',
padding: '4px 8px',
borderRadius: '4px',
fontSize: '12px',
zIndex: 1000
}}>
Saving...
</div>,
refTbody
)
)}
</> </>
); );
}); }
EditCellPortal.displayName = 'EditCellPortal';
// Основная функция getTableColumns
export const getTableColumns = ({ export const getTableColumns = ({
Cell, Cell,
EditCell, EditCell,
@ -93,127 +104,54 @@ export const getTableColumns = ({
onCellNumberClick, onCellNumberClick,
}) => { }) => {
const columnColors = { ...columnsConfig.colors }; const columnColors = { ...columnsConfig.colors };
const columns = structuredClone(columnsConfig.columns); const columns = [...columnsConfig.columns];
// Кэши для вычисленных значений const processColumns = (columns, EditCell, Cell) => {
const cellPropsCache = new WeakMap();
const editPropsCache = new WeakMap();
// Функция для получения кешированных пропсов Cell
const getCachedCellProps = (row, column, table) => {
const key = `${row.id}_${column.id}`;
if (!cellPropsCache.has(row)) {
cellPropsCache.set(row, {});
}
const rowCache = cellPropsCache.get(row);
if (rowCache[key]) {
// Проверяем, не изменились ли фильтры
const cached = rowCache[key];
const currentGlobalFilter = table.getState().globalFilter;
const currentColumnFilter = table.getState().columnFilters?.find(f => f.id === column.id)?.value;
if (cached.globalFilter === currentGlobalFilter &&
cached.columnFilter === currentColumnFilter) {
return cached;
}
}
const globalFilter = table.getState().globalFilter;
const columnFilter = table.getState().columnFilters?.find(f => f.id === column.id)?.value;
const props = {
globalFilter,
columnFilter,
isEditable: row.original?.row_type === 'INPUT' || false,
backgroundColor: columnColors[column.id]?.color_type?.[row.original?.row_type || row.row_type],
isUpdating: table.options.meta?.updatingCells?.[`${row.id}_${column.id}`],
_hash: `${globalFilter}_${columnFilter}_${row.id}_${column.id}`,
};
rowCache[key] = props;
return props;
};
// Функция для получения кешированных пропсов Edit
const getCachedEditProps = (row, column, table) => {
const key = `${row.id}_${column.id}`;
if (!editPropsCache.has(row)) {
editPropsCache.set(row, {});
}
const rowCache = editPropsCache.get(row);
if (rowCache[key]) {
return rowCache[key];
}
const props = {
isEditable: row.original?.row_type === 'INPUT' || false,
};
rowCache[key] = props;
return props;
};
// Оптимизированная функция processColumns
const processColumns = (columns) => {
columns.forEach((col) => { columns.forEach((col) => {
// Оптимизированный Cell col.Cell = ({ cell, table, column, row }) => (
col.Cell = ({ cell, table, column, row }) => { <Cell
const props = getCachedCellProps(row, column, table); row={row}
column={column}
cell={cell}
globalFilter={
table.getState().globalFilter
}
columnFilter={table.getState().columnFilters?.find(f => f.id === column.id)?.value}
isEditable={row.original?.row_type === 'INPUT' || false}
backgroundColor={columnColors[column.id]?.color_type?.[row.original?.row_type || row.row_type]}
color={columnColors[column.id]?.color_type?.['COLOR']}
isUpdating={table.options.meta?.updatingCells?.[`${row.id}_${column.id}`]}
/>
);
// Используем useMemo для мемоизации пропсов col.Edit = ({ cell, table, row, column }) => (
const cellProps = useMemo(() => ({ <EditCellPortal
row, cell={cell}
column, table={table}
cell, EditCell={EditCell}
...props, onError={onCellUpdateError}
}), [row.id, column.id, cell.getValue(), props._hash]); isEditable={row.original?.row_type === 'INPUT' || false}
/>
return <Cell {...cellProps} />; );
};
// Оптимизированный Edit
col.Edit = ({ cell, table, row, column }) => {
const props = getCachedEditProps(row, column, table);
// Мемоизируем компонент EditCellPortal
const editComponent = useMemo(() => (
<EditCellPortal
cell={cell}
table={table}
EditCell={EditCell}
onError={onCellUpdateError}
isEditable={props.isEditable}
/>
), [cell, table, EditCell, onCellUpdateError, props.isEditable]);
return editComponent;
};
// Рекурсивно обрабатываем вложенные колонки // Рекурсивно обрабатываем вложенные колонки
if (col.columns?.length) { if (col.columns?.length) {
processColumns(col.columns); processColumns(col.columns, EditCell, Cell);
} }
}); });
}; };
processColumns(columns); processColumns(columns, EditCell, Cell);
// Оптимизированная колонка с номерами строк
const rowNumber = { const rowNumber = {
accessorKey: 'sort_order', accessorKey: 'sort_order',
header: '#', header: '#',
size: 50, size: 50,
enableEditing: false, enableEditing: false,
Cell: ({ cell, row }) => { Cell: ({ cell, row }) => {
const handleClick = useCallback(() => { return <button onClick={() => { onCellNumberClick(row.id) }}>
onCellNumberClick(row.id); {cell.getValue() + ' '}
}, [row.id, onCellNumberClick]); </button>
return <button onClick={handleClick}>{cell.getValue() + ' '}</button>;
}, },
}; };