yantar/assets/Scripts/ui/ErrorLazyLoadList.ts
Georgy Shive 98e9d62db7 везде где только мог сделал с безопасной подпиской/отпиской через optional chaining
— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует
сделал ноды менеджеров списка оборудовани, деталей,
и аварий Persistent Node, чтобы при смене сцены не сбрасывалось
их состояние.
2025-05-11 13:33:08 +07:00

222 lines
7.2 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.

// scripts/ui/ErrorLazyLoadList.ts
import {
_decorator,
Component,
Prefab,
ScrollView,
instantiate,
UITransform,
Node,
Label,
director
} 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(Label)
public header: Label = null!;
@property
public spacing: number = 10;
private _data: ErrorItemData[] = [];
private _filteredData: ErrorItemData[] | null = null;
private _mode: 'errors' | 'details' = 'errors';
private _sensorDescription: SensorDescription = null!;
private _totalCount = 0;
private _loadedCount = 0;
private _itemHeight = 0;
private _content: Node = null!;
private _contentUI: UITransform = null!;
public get mode(): 'errors' | 'details' {
return this._mode;
}
onLoad() {
ErrorLazyLoadList.instance = this;
// Сохраняем узел, чтобы не уничтожался при loadScene
director.addPersistRootNode(this.node);
if (!this.scrollView.content) {
console.error('ScrollView.content is null!');
return;
}
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
// Вычисляем высоту одного элемента
const tempNode = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (tempUI) {
this._itemHeight = tempUI.height;
}
tempNode.destroy();
this._mode = 'errors';
this.waitForErrorManager();
// Подписываемся на скроллинг
this.scrollView.node.on('scrolling', this.onScrolling, this);
}
onDestroy() {
if (ErrorLazyLoadList.instance === this) {
ErrorLazyLoadList.instance = null;
}
// Отписываемся от обновлений ошибок
ErrorManager.instance?.node?.off('errors-updated', this.onDataUpdated, this);
// Отписываемся от скроллинга
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
// При желании можно убрать persist:
// director.removePersistRootNode(this.node);
}
private waitForErrorManager() {
if (!ErrorManager.instance) {
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);
}
}
private onScrolling() {
const offsetY = this.scrollView.getScrollOffset().y;
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
const contentHeight = this._contentUI.height;
if (offsetY + viewHeight + this._itemHeight * 2 >= contentHeight) {
this.loadNextBatch(20);
}
}
private loadNextBatch(batchSize: number) {
let currentData: any[] =
this._mode === 'errors'
? this._filteredData || this._data
: this._sensorDescription.fields;
if (this._loadedCount >= currentData.length) return;
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
for (let i = this._loadedCount; i < endIndex; i++) {
let item: Node;
if (this._mode === 'errors') {
item = instantiate(
this._filteredData ? this.errorItemNamedPrefab : this.errorItemPrefab
);
const componentName = this._filteredData
? 'ErrorItemNamedButton'
: 'ErrorItemButton';
const errorItem = item.getComponent(componentName) as
| ErrorItemNamedButton
| ErrorItemButton;
errorItem?.initialize(currentData[i]);
} else {
item = instantiate(this.sensorFieldItemPrefab);
item.getComponent(SensorFieldItem)?.setData(currentData[i]);
}
item.setPosition(
0,
-(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2),
0
);
this._content.addChild(item);
this._loadedCount++;
}
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
}
/** Фильтрация по конкретному оборудованию */
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);
}
/** Показ деталей датчика */
public showSensorDetails(data: { sensorName: string; fields: any[] }) {
this._mode = 'details';
this.header.string = `Детали ${data.sensorName}`;
this._sensorDescription = data as SensorDescription;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/** Переход обратно в список ошибок */
public showErrors() {
this.header.string = 'Список всех аварий';
this._mode = 'errors';
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}