yantar/assets/Scripts/ui/ErrorLazyLoadList.ts
2025-02-21 12:30:16 +07:00

112 lines
4.4 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 } from 'cc';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorManager } from '../stores/ErrorManager';
import { apiSensors } from '../stores/apiSensors';
const { ccclass, property } = _decorator;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
@property(Prefab)
public errorItemPrefab: Prefab = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
@property
public spacing: number = 10;
private _data: apiSensors[] = [];
private _totalCount: number = 0;
private _loadedCount: number = 0;
private _itemHeight: number = 0;
private _content: Node = null!;
private _contentUI: UITransform = null!;
onLoad() {
if (!this.scrollView.content) {
console.error("ScrollView.content равен null!");
return;
}
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
if (!this._contentUI) {
console.error("Узел content не имеет компонента UITransform!");
return;
}
// Определяем высоту элемента через префаб
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (!tempUI) {
console.error("В префабе отсутствует компонент UITransform!");
tempNode.destroy();
return;
}
this._itemHeight = tempUI.height;
tempNode.destroy();
this.waitForErrorManager();
}
// Рекурсивно ожидаем появления ErrorManager.instance
private waitForErrorManager() {
if (!ErrorManager.instance) {
console.warn("ErrorManager.instance не найден, повторная попытка...");
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
return;
}
// Подписываемся на событие обновления ошибок
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
// Если данные уже доступны, инициируем обновление списка:
this.onDataUpdated();
}
// Обработчик события обновления ошибок
private onDataUpdated() {
// Получаем массив ошибок из ErrorManager
this._data = ErrorManager.instance.getErrorList();
this._totalCount = this._data.length;
// Очищаем список и начинаем заново
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/**
* Загружает следующую партию элементов (batchSize элементов).
*/
loadNextBatch(batchSize: number) {
if (this._loadedCount >= this._totalCount) return;
const startIndex = this._loadedCount;
const endIndex = Math.min(this._loadedCount + batchSize, this._totalCount);
for (let i = startIndex; i < endIndex; i++) {
const item: Node = instantiate(this.errorItemPrefab);
const posY = - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1));
item.setPosition(0, posY, 0);
this._content.addChild(item);
// Получаем компонент ErrorItemButton с приведением типа
const errorItemButton = item.getComponent(ErrorItemButton) as ErrorItemButton;
if (errorItemButton) {
errorItemButton.initialize(this._data[i]);
}
}
this._loadedCount = endIndex;
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing) + this.spacing;
}
update(dt: number) {
if (!this.scrollView.content) return;
const threshold = 50;
const visibleHeight = this.scrollView.node.getComponent(UITransform)!.height;
const offset = Math.abs(this.scrollView.content.position.y);
if (offset >= (this._contentUI.height - visibleHeight - threshold)) {
if (this._loadedCount < this._totalCount) {
this.loadNextBatch(20);
}
}
}
}