(высота списка теперь корректно обновляется при изменении количества ошибок)
779 lines
34 KiB
TypeScript
779 lines
34 KiB
TypeScript
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, Label, NodePool, Vec3 } from 'cc';
|
||
import { ErrorItemData } from '../stores/ErrorItemData';
|
||
import { ErrorManager } from '../stores/ErrorManager';
|
||
import { ErrorItemButton } from '../ux/ErrorItemButton';
|
||
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
|
||
import { SensorDescription } from '../stores/SensorDescriptionField';
|
||
import { SensorFieldItem } from './SensorFieldItem';
|
||
import { MorphButtonWithButton } from '../ux/MorphButtonWithButton';
|
||
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("ErrorLazyLoadList")
|
||
export class ErrorLazyLoadList extends Component {
|
||
public static instance: ErrorLazyLoadList | null = null;
|
||
|
||
// Статические поля для сохранения состояния между сценами
|
||
private static _savedMode: "errors" | "details" = "errors";
|
||
private static _savedSensorDescription: SensorDescription | null = null;
|
||
private static _savedFilteredData: ErrorItemData[] | null = null;
|
||
|
||
@property(Prefab)
|
||
public errorItemPrefab: Prefab = null!;
|
||
|
||
@property(Prefab)
|
||
public sensorFieldItemPrefab: Prefab = null!;
|
||
|
||
@property(Prefab)
|
||
public errorItemNamedPrefab: Prefab = null!;
|
||
|
||
@property(ScrollView)
|
||
public scrollView: ScrollView = null!;
|
||
|
||
@property
|
||
public spacing: number = 10;
|
||
|
||
@property(Label)
|
||
public header: Label = null!;
|
||
|
||
@property
|
||
public visibleItemCount: number = 15; // Visible items buffer size
|
||
|
||
private _data: ErrorItemData[] = [];
|
||
private _filteredData: ErrorItemData[] | null = null;
|
||
private _mode: "errors" | "details" = "errors";
|
||
private _sensorDescription: SensorDescription = null!;
|
||
private _totalCount: number = 0;
|
||
private _itemHeight: number = 0; // Including spacing
|
||
private _content: Node = null!;
|
||
private _contentUI: UITransform = null!;
|
||
|
||
// Lazy-created NodePools
|
||
private _errorItemPool: NodePool | null = null;
|
||
private _namedErrorItemPool: NodePool | null = null;
|
||
private _sensorFieldItemPools: Map<string, NodePool> = new Map(); // Пул для каждого датчика
|
||
private _activeSensorNames: Set<string> = new Set(); // Отслеживаем активные датчики
|
||
private _activeSensorFieldItems: Map<string, Set<Node>> = new Map(); // Отслеживаем активные элементы для каждого датчика
|
||
|
||
// Active items tracking
|
||
private _activeItems: Node[] = [];
|
||
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
|
||
private _firstVisibleIndex: number = 0;
|
||
private _lastVisibleIndex: number = 0;
|
||
|
||
public get mode(): "errors" | "details" {
|
||
return this._mode;
|
||
}
|
||
|
||
onLoad() {
|
||
ErrorLazyLoadList.instance = this;
|
||
|
||
if (!this.scrollView.content) {
|
||
console.error("ScrollView.content is null!");
|
||
return;
|
||
}
|
||
|
||
this._content = this.scrollView.content;
|
||
this._contentUI = this._content.getComponent(UITransform)!;
|
||
|
||
// Calculate item height including spacing
|
||
const tempNode: Node = instantiate(this.errorItemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
this._itemHeight = tempUI!.height + this.spacing;
|
||
tempNode.destroy();
|
||
|
||
// Восстанавливаем сохраненное состояние
|
||
this._mode = ErrorLazyLoadList._savedMode;
|
||
if (ErrorLazyLoadList._savedSensorDescription) {
|
||
this._sensorDescription = ErrorLazyLoadList._savedSensorDescription;
|
||
}
|
||
this._filteredData = ErrorLazyLoadList._savedFilteredData;
|
||
|
||
// Устанавливаем правильный заголовок
|
||
if (this._mode === "details" && this._sensorDescription) {
|
||
this.header.string = `Детали ${this._sensorDescription.sensorName}`;
|
||
} else if (this._filteredData) {
|
||
this.header.string = `Аварии на ${this._filteredData[0]?.sensorName || "неизвестно"}`;
|
||
} else {
|
||
this.header.string = "Список всех аварий";
|
||
}
|
||
|
||
this.waitForErrorManager();
|
||
this.scrollView.node.on('scrolling', this.onScrolling, this);
|
||
}
|
||
|
||
onDestroy() {
|
||
// Сохраняем текущее состояние перед уничтожением
|
||
ErrorLazyLoadList._savedMode = this._mode;
|
||
ErrorLazyLoadList._savedSensorDescription = this._sensorDescription;
|
||
ErrorLazyLoadList._savedFilteredData = this._filteredData;
|
||
|
||
// Clean up event listeners
|
||
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
|
||
|
||
const errorManagerNode = (ErrorManager.instance as any)?.node;
|
||
if (errorManagerNode) {
|
||
errorManagerNode.off('errors-updated', this.onDataUpdated, this);
|
||
}
|
||
|
||
// Clear pools and active items tracking
|
||
this._errorItemPool?.clear();
|
||
this._namedErrorItemPool?.clear();
|
||
this._sensorFieldItemPools.forEach(pool => pool.clear());
|
||
this._sensorFieldItemPools.clear();
|
||
this._activeSensorNames.clear();
|
||
this._activeSensorFieldItems.clear();
|
||
|
||
if (ErrorLazyLoadList.instance === this) {
|
||
ErrorLazyLoadList.instance = null;
|
||
}
|
||
}
|
||
|
||
private getOrCreateErrorItemPool(): NodePool {
|
||
if (!this._errorItemPool) {
|
||
this._errorItemPool = new NodePool();
|
||
for (let i = 0; i < this.visibleItemCount; i++) {
|
||
this._errorItemPool.put(instantiate(this.errorItemPrefab));
|
||
}
|
||
}
|
||
return this._errorItemPool;
|
||
}
|
||
|
||
private getOrCreateNamedErrorItemPool(): NodePool {
|
||
if (!this._namedErrorItemPool) {
|
||
this._namedErrorItemPool = new NodePool();
|
||
for (let i = 0; i < this.visibleItemCount; i++) {
|
||
this._namedErrorItemPool.put(instantiate(this.errorItemNamedPrefab));
|
||
}
|
||
}
|
||
return this._namedErrorItemPool;
|
||
}
|
||
|
||
private getOrCreateSensorFieldItemPool(sensorName: string): NodePool {
|
||
// Используем один общий пул для всех датчиков
|
||
if (!this._sensorFieldItemPools.has('common')) {
|
||
const pool = new NodePool();
|
||
// Создаем пул достаточного размера
|
||
const poolSize = Math.max(this.visibleItemCount, 20);
|
||
for (let i = 0; i < poolSize; i++) {
|
||
const item = instantiate(this.sensorFieldItemPrefab);
|
||
// Сбрасываем состояние кнопок при создании
|
||
this.resetSensorFieldItemState(item);
|
||
pool.put(item);
|
||
}
|
||
this._sensorFieldItemPools.set('common', pool);
|
||
}
|
||
return this._sensorFieldItemPools.get('common')!;
|
||
}
|
||
|
||
private resetSensorFieldItemState(item: Node) {
|
||
// Сбрасываем состояние компонента SensorFieldItem
|
||
const sensorFieldItem = item.getComponent(SensorFieldItem);
|
||
if (sensorFieldItem) {
|
||
sensorFieldItem.resetState();
|
||
sensorFieldItem.reinitialize();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Полностью очищает все пулы и уничтожает элементы
|
||
*/
|
||
private clearAllPools() {
|
||
console.log('[ErrorLazyLoadList] Clearing all pools');
|
||
|
||
// Очищаем и уничтожаем элементы в пулах
|
||
if (this._errorItemPool) {
|
||
this._errorItemPool.clear();
|
||
this._errorItemPool = null;
|
||
}
|
||
|
||
if (this._namedErrorItemPool) {
|
||
this._namedErrorItemPool.clear();
|
||
this._namedErrorItemPool = null;
|
||
}
|
||
|
||
// Очищаем пулы датчиков
|
||
this._sensorFieldItemPools.forEach(pool => {
|
||
pool.clear();
|
||
});
|
||
this._sensorFieldItemPools.clear();
|
||
|
||
this._activeSensorNames.clear();
|
||
this._activeSensorFieldItems.clear();
|
||
}
|
||
|
||
private waitForErrorManager() {
|
||
if (!ErrorManager.instance) {
|
||
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
|
||
return;
|
||
}
|
||
|
||
// ErrorManager extends Component, so it has a node property
|
||
const errorManagerNode = (ErrorManager.instance as any).node;
|
||
if (errorManagerNode && typeof errorManagerNode.on === 'function') {
|
||
errorManagerNode.on('errors-updated', this.onDataUpdated, this);
|
||
} else {
|
||
console.warn("Could not subscribe to ErrorManager events - node not found");
|
||
}
|
||
|
||
// Обновляем отображение в зависимости от режима
|
||
if (this._mode === "errors") {
|
||
this.onDataUpdated();
|
||
} else if (this._mode === "details") {
|
||
// Для режима details обновляем размеры и элементы
|
||
this.updateVisibleItems(true); // Принудительно обновляем (включая высоту)
|
||
}
|
||
}
|
||
|
||
private onDataUpdated() {
|
||
if (this._mode !== "errors") return;
|
||
|
||
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
|
||
const flattened: ErrorItemData[] = [];
|
||
|
||
for (const sensorName in apiErrors) {
|
||
for (const err of apiErrors[sensorName]) {
|
||
flattened.push({ sensorName, alarmCode: err.alarmCode, description: err.description, timestamp: err.timestamp });
|
||
}
|
||
}
|
||
|
||
const oldDataLength = this._data.length;
|
||
this._data = flattened;
|
||
|
||
// Update both filtered and unfiltered views
|
||
if (this._filteredData) {
|
||
// If we have a filter, reapply it to the new data
|
||
const currentFilter = this._filteredData.length > 0 ? this._filteredData[0].sensorName : '';
|
||
if (currentFilter) {
|
||
const oldFilteredLength = this._filteredData.length;
|
||
this._filteredData = this._data.filter(item => item.sensorName === currentFilter);
|
||
this._totalCount = this._filteredData.length;
|
||
|
||
// Принудительно обновляем высоту если изменилось количество отфильтрованных элементов
|
||
if (oldFilteredLength !== this._filteredData.length) {
|
||
this.updateVisibleItems(true);
|
||
return;
|
||
}
|
||
}
|
||
} else {
|
||
this._totalCount = this._data.length;
|
||
|
||
// Принудительно обновляем высоту если изменилось общее количество элементов
|
||
if (oldDataLength !== this._data.length) {
|
||
this.updateVisibleItems(true);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// Просто обновляем видимые элементы без уничтожения
|
||
this.updateVisibleItems();
|
||
}
|
||
|
||
private onScrolling() {
|
||
this.updateVisibleItems();
|
||
}
|
||
|
||
private updateVisibleItems(forceUpdate: boolean = false) {
|
||
const totalItems = this.getTotalItems();
|
||
|
||
// При принудительном обновлении всегда обновляем высоту контента
|
||
// Также обновляем высоту если изменилось общее количество элементов
|
||
if (forceUpdate || this._totalCount !== totalItems) {
|
||
this._totalCount = totalItems;
|
||
this.updateContentHeight();
|
||
}
|
||
|
||
const scrollY = this.scrollView.getScrollOffset().y;
|
||
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||
|
||
// Calculate the first visible item index based on scroll position
|
||
const newFirstVisible = Math.floor(Math.max(0, scrollY) / this._itemHeight);
|
||
|
||
// Handle the case when there are no items
|
||
if (totalItems <= 0) {
|
||
this.hideAllItems();
|
||
return;
|
||
}
|
||
|
||
const newLastVisible = Math.min(
|
||
newFirstVisible + Math.ceil(viewHeight / this._itemHeight) + 2,
|
||
totalItems - 1
|
||
);
|
||
|
||
// Always update if visible range changed OR if forced
|
||
const needsUpdate = forceUpdate ||
|
||
newFirstVisible !== this._firstVisibleIndex ||
|
||
newLastVisible !== this._lastVisibleIndex;
|
||
|
||
if (!needsUpdate) {
|
||
return;
|
||
}
|
||
|
||
this._firstVisibleIndex = Math.max(0, newFirstVisible);
|
||
this._lastVisibleIndex = Math.max(0, newLastVisible);
|
||
|
||
this.updatePoolItems();
|
||
}
|
||
|
||
private hideAllItems() {
|
||
// Return all active items to their pools
|
||
// Создаем копию массива, так как returnItemToPool может изменять _activeItems
|
||
const itemsToReturn = [...this._activeItems];
|
||
for (const item of itemsToReturn) {
|
||
this.returnItemToPool(item);
|
||
}
|
||
this._activeItems = [];
|
||
this._activeItemsData = []; // Очищаем данные отслеживания
|
||
}
|
||
|
||
private returnItemToPool(item: Node) {
|
||
if (!item || !item.isValid) return;
|
||
|
||
item.active = false;
|
||
item.removeFromParent();
|
||
|
||
// Determine which pool this item belongs to and return it
|
||
if (item.getComponent(ErrorItemButton)) {
|
||
this.getOrCreateErrorItemPool().put(item);
|
||
} else if (item.getComponent(ErrorItemNamedButton)) {
|
||
this.getOrCreateNamedErrorItemPool().put(item);
|
||
} else if (item.getComponent(SensorFieldItem)) {
|
||
// Для датчиков НЕ возвращаем в пул, а уничтожаем для гарантии чистого состояния
|
||
console.log(`[ErrorLazyLoadList] Destroying SensorFieldItem instead of pooling`);
|
||
|
||
// Удаляем из активных элементов
|
||
const sensorFieldItem = item.getComponent(SensorFieldItem);
|
||
if (sensorFieldItem && sensorFieldItem.sensorName) {
|
||
const activeItems = this._activeSensorFieldItems.get(sensorFieldItem.sensorName);
|
||
if (activeItems) {
|
||
activeItems.delete(item);
|
||
console.log(`[ErrorLazyLoadList] Removed item from active items for ${sensorFieldItem.sensorName}, remaining: ${activeItems.size}`);
|
||
}
|
||
}
|
||
|
||
if (sensorFieldItem) {
|
||
sensorFieldItem.resetState(); // Сбрасываем состояние перед уничтожением
|
||
}
|
||
item.destroy(); // Полностью уничтожаем элемент
|
||
}
|
||
}
|
||
|
||
private updatePoolItems() {
|
||
const currentData = this.getCurrentData();
|
||
const itemsToShow = Math.min(
|
||
this._lastVisibleIndex - this._firstVisibleIndex + 1,
|
||
currentData.length - this._firstVisibleIndex
|
||
);
|
||
|
||
// Определяем нужный пул для текущего режима
|
||
let currentPool: NodePool;
|
||
let expectedComponentType: string;
|
||
|
||
if (this._mode === "errors") {
|
||
if (this._filteredData) {
|
||
currentPool = this.getOrCreateNamedErrorItemPool();
|
||
expectedComponentType = "ErrorItemNamedButton";
|
||
} else {
|
||
currentPool = this.getOrCreateErrorItemPool();
|
||
expectedComponentType = "ErrorItemButton";
|
||
}
|
||
} else if (this._mode === "details") {
|
||
const sensorName = this._sensorDescription.sensorName;
|
||
currentPool = this.getOrCreateSensorFieldItemPool(sensorName);
|
||
expectedComponentType = "SensorFieldItem";
|
||
this._activeSensorNames.add(sensorName);
|
||
|
||
// Инициализируем Set для активных элементов этого датчика, если его нет
|
||
if (!this._activeSensorFieldItems.has(sensorName)) {
|
||
this._activeSensorFieldItems.set(sensorName, new Set());
|
||
}
|
||
} else {
|
||
return;
|
||
}
|
||
|
||
// Проверяем совместимость существующих элементов с текущим режимом
|
||
const incompatibleItems: Node[] = [];
|
||
for (const item of this._activeItems) {
|
||
const hasCorrectComponent = item.getComponent(expectedComponentType);
|
||
if (!hasCorrectComponent) {
|
||
incompatibleItems.push(item);
|
||
}
|
||
}
|
||
|
||
// Убираем несовместимые элементы
|
||
for (const item of incompatibleItems) {
|
||
const index = this._activeItems.indexOf(item);
|
||
if (index !== -1) {
|
||
this._activeItems.splice(index, 1);
|
||
this._activeItemsData.splice(index, 1);
|
||
this.returnItemToPool(item);
|
||
}
|
||
}
|
||
|
||
// Переиспользуем существующие элементы или создаем недостающие
|
||
const targetActiveCount = Math.max(0, itemsToShow);
|
||
|
||
// Если элементов больше чем нужно - скрываем лишние
|
||
while (this._activeItems.length > targetActiveCount) {
|
||
const item = this._activeItems.pop()!;
|
||
this._activeItemsData.pop();
|
||
this.returnItemToPool(item);
|
||
}
|
||
|
||
// Если элементов меньше чем нужно - добавляем новые
|
||
while (this._activeItems.length < targetActiveCount) {
|
||
let item: Node | null = null;
|
||
|
||
if (this._mode === "details") {
|
||
// Для датчиков всегда создаем новые элементы
|
||
item = this.createItemForCurrentMode();
|
||
} else {
|
||
// Для ошибок используем пул
|
||
item = currentPool.get() || this.createItemForCurrentMode();
|
||
}
|
||
|
||
if (!item) break;
|
||
|
||
this._content.addChild(item);
|
||
item.active = true;
|
||
this._activeItems.push(item);
|
||
this._activeItemsData.push(null); // Placeholder для новых элементов
|
||
|
||
// Если это элемент датчика, добавляем его в активные элементы
|
||
if (this._mode === "details") {
|
||
const sensorName = this._sensorDescription.sensorName;
|
||
let activeItems = this._activeSensorFieldItems.get(sensorName);
|
||
if (!activeItems) {
|
||
activeItems = new Set();
|
||
this._activeSensorFieldItems.set(sensorName, activeItems);
|
||
}
|
||
activeItems.add(item);
|
||
console.log(`[ErrorLazyLoadList] Added SensorFieldItem to active items for ${sensorName}, total: ${activeItems.size}`);
|
||
}
|
||
}
|
||
|
||
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
|
||
for (let i = 0; i < this._activeItems.length; i++) {
|
||
const dataIndex = this._firstVisibleIndex + i;
|
||
const item = this._activeItems[i];
|
||
|
||
if (dataIndex >= 0 && dataIndex < currentData.length) {
|
||
const newData = currentData[dataIndex];
|
||
const oldData = this._activeItemsData[i];
|
||
|
||
// Для новых элементов датчиков всегда обновляем данные
|
||
// Для остальных - сравниваем данные и обновляем только если изменились
|
||
const isNewSensorItem = this._mode === "details" && !oldData;
|
||
|
||
// Для датчиков проверяем изменения в значениях полей более детально
|
||
let dataChanged = false;
|
||
if (this._mode === "details" && oldData && newData) {
|
||
dataChanged = oldData.name !== newData.name ||
|
||
oldData.value !== newData.value ||
|
||
oldData.unit !== newData.unit ||
|
||
oldData.description !== newData.description;
|
||
}
|
||
|
||
const needsUpdate = isNewSensorItem || !oldData ||
|
||
dataChanged ||
|
||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
|
||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
|
||
|
||
if (needsUpdate) {
|
||
// Обновляем данные компонента
|
||
const component = this.getComponentForCurrentMode(item);
|
||
try {
|
||
switch (this._mode) {
|
||
case "errors":
|
||
if (component && 'initialize' in component && typeof component.initialize === 'function') {
|
||
(component as ErrorItemButton | ErrorItemNamedButton).initialize(newData);
|
||
}
|
||
break;
|
||
case "details":
|
||
if (component && 'setData' in component && typeof component.setData === 'function') {
|
||
console.log(`[ErrorLazyLoadList] Updating SensorFieldItem data: ${newData.name}`);
|
||
// Для новых элементов используем setData (полная инициализация)
|
||
// Для существующих элементов используем updateData (сохранение состояния UI)
|
||
if (isNewSensorItem) {
|
||
(component as SensorFieldItem).setData(newData);
|
||
} else {
|
||
(component as SensorFieldItem).updateData(newData);
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
|
||
// Сохраняем новые данные для будущих сравнений
|
||
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
|
||
} catch (e) {
|
||
console.warn("Error updating item component:", e);
|
||
}
|
||
}
|
||
|
||
// Позиционируем элемент (это нужно делать всегда для виртуализации)
|
||
item.setPosition(0, -(dataIndex * this._itemHeight + this._itemHeight / 2 - this.spacing / 2), 0);
|
||
|
||
// Показываем элемент только если он еще не виден
|
||
if (!item.active) {
|
||
item.active = true;
|
||
}
|
||
} else {
|
||
// Скрываем элементы вне диапазона
|
||
if (item.active) {
|
||
item.active = false;
|
||
}
|
||
this._activeItemsData[i] = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
private createItemForCurrentMode(): Node | null {
|
||
if (this._mode === "errors") {
|
||
if (this._filteredData) {
|
||
return instantiate(this.errorItemNamedPrefab);
|
||
} else {
|
||
return instantiate(this.errorItemPrefab);
|
||
}
|
||
} else if (this._mode === "details") {
|
||
// Для датчиков всегда создаем новые элементы для гарантии чистого состояния
|
||
if (this._sensorDescription && this._sensorDescription.sensorName) {
|
||
console.log(`[ErrorLazyLoadList] Creating fresh SensorFieldItem for ${this._sensorDescription.sensorName}`);
|
||
const item = instantiate(this.sensorFieldItemPrefab);
|
||
// Сбрасываем состояние нового элемента
|
||
this.resetSensorFieldItemState(item);
|
||
return item;
|
||
}
|
||
return null;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
private getComponentForCurrentMode(item: Node): Component | null {
|
||
if (this._mode === "errors") {
|
||
if (this._filteredData) {
|
||
return item.getComponent(ErrorItemNamedButton);
|
||
} else {
|
||
return item.getComponent(ErrorItemButton);
|
||
}
|
||
} else if (this._mode === "details") {
|
||
return item.getComponent(SensorFieldItem);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
private getCurrentData(): any[] {
|
||
if (this._mode === "errors") {
|
||
return this._filteredData || this._data;
|
||
} else if (this._mode === "details") {
|
||
return this._sensorDescription?.fields || [];
|
||
}
|
||
return [];
|
||
}
|
||
|
||
private getTotalItems(): number {
|
||
return this.getCurrentData().length;
|
||
}
|
||
|
||
private updateContentHeight() {
|
||
const totalItems = this.getTotalItems();
|
||
const newHeight = totalItems * this._itemHeight;
|
||
const oldHeight = this._contentUI.height;
|
||
|
||
if (oldHeight !== newHeight) {
|
||
console.log(`[ErrorLazyLoadList] Updating content height: ${oldHeight} -> ${newHeight} (items: ${totalItems})`);
|
||
this._contentUI.height = newHeight;
|
||
}
|
||
}
|
||
|
||
private preserveScrollPosition(callback: () => void) {
|
||
const oldOffset = this.scrollView.getScrollOffset();
|
||
callback();
|
||
this.scheduleOnce(() => {
|
||
this.scrollView.scrollToOffset(oldOffset, 0.1);
|
||
}, 0);
|
||
}
|
||
|
||
/**
|
||
* Фильтрует список ошибок по имени оборудования.
|
||
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
|
||
*/
|
||
public filterBySensor(sensorName: string) {
|
||
// Проверяем, действительно ли меняется фильтр
|
||
const isNewFilter = !this._filteredData ||
|
||
this._filteredData.length === 0 ||
|
||
this._filteredData[0].sensorName !== sensorName;
|
||
|
||
this.preserveScrollPosition(() => {
|
||
// Уничтожаем элементы и очищаем пулы если меняется фильтр
|
||
if (isNewFilter) {
|
||
this.hideAllItems();
|
||
this.clearAllPools(); // Полностью очищаем пулы
|
||
}
|
||
|
||
this._mode = "errors";
|
||
this.header.string = `Аварии на ${sensorName}`;
|
||
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
|
||
this._totalCount = this._filteredData.length;
|
||
|
||
// Принудительно обновляем данные
|
||
this.updateVisibleItems(true);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
|
||
*/
|
||
public resetFilter() {
|
||
// Проверяем, действительно ли есть активный фильтр
|
||
const hasActiveFilter = this._filteredData !== null;
|
||
|
||
this.preserveScrollPosition(() => {
|
||
// Уничтожаем элементы и очищаем пулы если был активный фильтр
|
||
if (hasActiveFilter) {
|
||
this.hideAllItems();
|
||
this.clearAllPools(); // Полностью очищаем пулы
|
||
}
|
||
|
||
this.header.string = "Список всех аварий";
|
||
this._mode = "errors";
|
||
this._filteredData = null;
|
||
this._totalCount = this._data.length;
|
||
|
||
// Принудительно обновляем данные
|
||
this.updateVisibleItems(true);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Принимает данные описания оборудования и переключает режим отображения в "details".
|
||
* @param data Объект с деталями датчика.
|
||
*/
|
||
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
|
||
// Проверяем, действительно ли меняется датчик или режим
|
||
const isNewSensor = !this._sensorDescription || this._sensorDescription.sensorName !== data.sensorName;
|
||
const isModeChange = this._mode !== "details";
|
||
|
||
this.preserveScrollPosition(() => {
|
||
// Уничтожаем элементы и очищаем пулы если меняется датчик или режим
|
||
if (isNewSensor || isModeChange) {
|
||
this.hideAllItems();
|
||
this.clearAllPools(); // Полностью очищаем все пулы
|
||
}
|
||
|
||
this._mode = "details";
|
||
this.header.string = `Детали ${data.sensorName}`;
|
||
this._sensorDescription = {
|
||
sensorName: data.sensorName,
|
||
fields: data.fields || []
|
||
};
|
||
|
||
// Принудительно обновляем данные
|
||
this.updateVisibleItems(true);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Обновляет данные датчика без сброса UI состояния (для периодических обновлений).
|
||
* @param data Объект с деталями датчика.
|
||
*/
|
||
public updateSensorDetails(data: { sensorName: string, fields: any[] }) {
|
||
// Обновляем только если мы в режиме details и это тот же датчик
|
||
if (this._mode !== "details" || !this._sensorDescription ||
|
||
this._sensorDescription.sensorName !== data.sensorName) {
|
||
return;
|
||
}
|
||
|
||
console.log(`[ErrorLazyLoadList] updateSensorDetails: ${data.sensorName}, fields count: ${data.fields?.length || 0}`);
|
||
|
||
// Сохраняем старое количество полей для сравнения
|
||
const oldFieldsCount = this._sensorDescription.fields?.length || 0;
|
||
const newFieldsCount = data.fields?.length || 0;
|
||
|
||
// Обновляем данные
|
||
this._sensorDescription = {
|
||
sensorName: data.sensorName,
|
||
fields: data.fields || []
|
||
};
|
||
|
||
// Принудительно сбрасываем данные отслеживания для принудительного обновления
|
||
this._activeItemsData = this._activeItemsData.map(() => null);
|
||
|
||
// Принудительно обновляем все активные элементы датчика
|
||
this.forceUpdateActiveSensorItems(data.sensorName, data.fields);
|
||
|
||
// Если изменилось количество полей, принудительно обновляем высоту контента
|
||
if (oldFieldsCount !== newFieldsCount) {
|
||
this.updateVisibleItems(true);
|
||
} else {
|
||
// Обновляем видимые элементы без принудительного обновления высоты
|
||
this.updateVisibleItems(false);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Принудительно обновляет все активные элементы конкретного датчика
|
||
*/
|
||
private forceUpdateActiveSensorItems(sensorName: string, fields: any[]) {
|
||
const activeItems = this._activeSensorFieldItems.get(sensorName);
|
||
if (!activeItems || activeItems.size === 0) {
|
||
console.log(`[ErrorLazyLoadList] No active items found for sensor ${sensorName}`);
|
||
return;
|
||
}
|
||
|
||
console.log(`[ErrorLazyLoadList] Force updating ${activeItems.size} active items for sensor ${sensorName}`);
|
||
|
||
// Обновляем каждый активный элемент
|
||
let itemIndex = 0;
|
||
for (const item of activeItems) {
|
||
if (!item.isValid || !item.active) {
|
||
continue;
|
||
}
|
||
|
||
const component = item.getComponent(SensorFieldItem);
|
||
if (component && itemIndex < fields.length) {
|
||
const fieldData = fields[itemIndex];
|
||
console.log(`[ErrorLazyLoadList] Force updating item ${itemIndex}: ${fieldData.name} = ${fieldData.value}`);
|
||
// Используем updateData() вместо setData() для сохранения состояния UI
|
||
component.updateData(fieldData);
|
||
itemIndex++;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
|
||
*/
|
||
public showErrors() {
|
||
// Проверяем, действительно ли меняется режим
|
||
const isModeChange = this._mode !== "errors";
|
||
|
||
this.preserveScrollPosition(() => {
|
||
// Уничтожаем элементы и очищаем пулы если меняется режим
|
||
if (isModeChange) {
|
||
this.hideAllItems();
|
||
this.clearAllPools(); // Полностью очищаем все пулы
|
||
}
|
||
|
||
this._mode = "errors";
|
||
this.header.string = "Список всех аварий";
|
||
this._filteredData = null;
|
||
this._totalCount = this._data.length;
|
||
|
||
// Принудительно обновляем данные
|
||
this.updateVisibleItems(true);
|
||
});
|
||
}
|
||
|
||
private updateSensorFieldItem(item: Node, data: any, dataIndex: number) {
|
||
const component = item.getComponent(SensorFieldItem);
|
||
if (component) {
|
||
component.setData(data);
|
||
}
|
||
}
|
||
|
||
private cleanupUnusedSensorPools() {
|
||
// Теперь у нас один общий пул, поэтому просто очищаем неиспользуемые ссылки
|
||
this._activeSensorNames.clear();
|
||
this._activeSensorFieldItems.clear();
|
||
}
|
||
} |