yantar/assets/Scripts/ui/ErrorLazyLoadList.ts
Georgy Shive 7af1d174fc добавлено вычисление размера префаба для
последующей отрисовки следующего префаба списка
2025-03-24 19:23:57 +07:00

246 lines
9.7 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 } 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';
const { ccclass, property } = _decorator;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
// Синглтон для доступа из других мест
public static instance: ErrorLazyLoadList | 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!;
// Массив для хранения всех ошибок, полученных с API (плоский список)
private _data: ErrorItemData[] = [];
// Массив для хранения отфильтрованных данных (если фильтр активирован)
private _filteredData: ErrorItemData[] | null = null;
// Дополнительно: режим отображения – ошибки или детали
private _mode: "errors" | "details" = "errors";
// Данные описания датчика (SensorDescription) для режима "details"
private _sensorDescription: SensorDescription = null!;
private _totalCount: number = 0;
private _loadedCount: number = 0;
private _itemHeight: number = 0;
private _content: Node = null!;
private _contentUI: UITransform = null!;
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)!;
if (!this._contentUI) {
console.error("Content node does not have UITransform component!");
return;
}
// Определяем высоту элемента через префаб (используем errorItemPrefab)
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (!tempUI) {
console.error("Prefab missing UITransform component!");
tempNode.destroy();
return;
}
this._itemHeight = tempUI.height;
tempNode.destroy();
// Изначально работаем в режиме "errors"
this._mode = "errors";
this.waitForErrorManager();
}
onDestroy() {
if (ErrorLazyLoadList.instance === this) {
ErrorLazyLoadList.instance = null;
}
}
private waitForErrorManager() {
if (!ErrorManager.instance) {
console.warn("ErrorManager.instance not found, retrying...");
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
return;
}
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
this.onDataUpdated();
}
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;
if (!this._filteredData) {
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}
loadNextBatch(batchSize: number) {
let currentData: any[] = [];
if (this._mode === "errors") {
currentData = this._filteredData || this._data;
} else if (this._mode === "details") {
currentData = this._sensorDescription ? this._sensorDescription.fields : [];
}
if (this._loadedCount >= currentData.length) return;
// Вычисляем суммарную высоту уже отрисованных элементов
let cumulativeHeight = 0;
for (let i = 0; i < this._content.children.length; i++) {
const child = this._content.children[i];
const childHeight = child.getComponent(UITransform)?.height || 0;
cumulativeHeight += childHeight + this.spacing;
}
// Загружаем следующую порцию элементов
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
for (let i = this._loadedCount; i < endIndex; i++) {
let item: Node;
if (this._mode === "errors") {
if (this._filteredData) {
item = instantiate(this.errorItemNamedPrefab);
const errorItemNamedButton = item.getComponent(ErrorItemNamedButton);
if (errorItemNamedButton) {
errorItemNamedButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemNamedButton не найден на префабе.");
}
} else {
item = instantiate(this.errorItemPrefab);
const errorItemButton = item.getComponent(ErrorItemButton);
if (errorItemButton) {
errorItemButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemButton не найден на префабе.");
}
}
} else if (this._mode === "details") {
item = instantiate(this.sensorFieldItemPrefab);
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
sensorFieldItem.setData(currentData[i]);
} else {
console.warn("Компонент SensorFieldItem не найден на префабе.");
}
} else {
console.error("Неизвестный режим: " + this._mode);
continue;
}
// Получаем высоту элемента после установки данных
const itemHeight = item.getComponent(UITransform)?.height || this._itemHeight;
// Устанавливаем позицию: по Y = -(cumulativeHeight + itemHeight/2)
item.setPosition(0, - (cumulativeHeight + itemHeight / 2), 0);
cumulativeHeight += itemHeight + this.spacing;
this._content.addChild(item);
}
this._loadedCount = endIndex;
// Обновляем высоту контейнера
this._contentUI.height = cumulativeHeight;
}
/**
* В
/**
* Фильтрует список ошибок по имени оборудования.
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
*/
public filterBySensor(sensorName: string) {
this._mode = "errors";
this.header.string = `Аварии на ${sensorName}`;
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
this._totalCount = this._filteredData.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/**
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
*/
public resetFilter() {
this.header.string = "Список всех аварий";
this._mode = "errors";
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/**
* Принимает данные описания оборудования и переключает режим отображения в "details".
* @param data Объект с деталями датчика.
*/
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
this._mode = "details";
this.header.string = `Детали ${data.sensorName}`;
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields
};
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
this._mode = "errors";
this.header.string = "Список всех аварий";
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}