yantar/assets/Scripts/ui/ErrorLazyLoadList.ts
2025-05-27 13:58:07 +07:00

641 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 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 });
}
}
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) {
this._filteredData = this._data.filter(item => item.sensorName === currentFilter);
this._totalCount = this._filteredData.length;
}
} else {
this._totalCount = this._data.length;
}
// Просто обновляем видимые элементы без уничтожения
this.updateVisibleItems();
}
private onScrolling() {
this.updateVisibleItems();
}
private updateVisibleItems(forceUpdate: boolean = false) {
// При принудительном обновлении всегда обновляем высоту контента
if (forceUpdate) {
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);
const totalItems = this.getTotalItems();
// 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)) {
// Для датчиков возвращаем в общий пул
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
// Сбрасываем состояние перед возвратом в пул
sensorFieldItem.resetState();
// Возвращаем в общий пул
const pool = this.getOrCreateSensorFieldItemPool('');
pool.put(item);
}
}
}
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);
} 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) {
const item = this._mode === "details"
? this.createItemForCurrentMode()
: 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;
const activeItems = this._activeSensorFieldItems.get(sensorName);
if (activeItems) {
activeItems.add(item);
}
}
}
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
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 needsUpdate = !oldData ||
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') {
(component as SensorFieldItem).setData(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) {
const pool = this.getOrCreateSensorFieldItemPool(this._sensorDescription.sensorName);
let item = pool.get();
if (!item) {
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();
this._contentUI.height = totalItems * this._itemHeight;
}
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._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.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;
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если меняется датчик
if (isNewSensor) {
this.hideAllItems();
// Очищаем пулы неактивных датчиков при смене
this.cleanupUnusedSensorPools();
}
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;
}
// Просто обновляем данные без сброса UI
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields || []
};
// Обновляем видимые элементы без принудительного сброса
this.updateVisibleItems(false);
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
// Проверяем, действительно ли меняется режим
const isModeChange = this._mode !== "errors";
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если меняется режим
if (isModeChange) {
this.hideAllItems();
}
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();
}
}