138 lines
5.4 KiB
TypeScript
138 lines
5.4 KiB
TypeScript
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, MeshRenderer } from 'cc';
|
||
import { ItemButton } from '../ux/ItemButton';
|
||
import { apiSensors } from '../stores/apiSensors';
|
||
import { EquipmentManager } from '../stores/EquipmentManager';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("LazyLoadList")
|
||
export class LazyLoadList extends Component {
|
||
|
||
@property(Prefab)
|
||
public itemPrefab: Prefab = null!;
|
||
|
||
@property(ScrollView)
|
||
public scrollView: ScrollView = null!;
|
||
|
||
// Добавляем свойство для передачи ноды Equipment
|
||
@property(Node)
|
||
public equipmentNode: Node = 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.itemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
if (!tempUI) {
|
||
console.error("В префабе отсутствует компонент UITransform!");
|
||
tempNode.destroy();
|
||
return;
|
||
}
|
||
this._itemHeight = tempUI.height;
|
||
tempNode.destroy();
|
||
|
||
// Ожидаем появления EquipmentManager.instance
|
||
this.waitForEquipmentManager();
|
||
}
|
||
|
||
// Рекурсивно ожидаем появления EquipmentManager.instance
|
||
private waitForEquipmentManager() {
|
||
if (!EquipmentManager.instance) {
|
||
console.warn("EquipmentManager.instance не найден, повторная попытка...");
|
||
this.scheduleOnce(() => { this.waitForEquipmentManager(); }, 0.1);
|
||
return;
|
||
}
|
||
// Подписываемся на событие обновления данных
|
||
EquipmentManager.instance.node.on('data-updated', this.onDataUpdated, this);
|
||
// Если данные уже загружены, инициируем обновление списка:
|
||
this.onDataUpdated();
|
||
}
|
||
|
||
// Обработчик события обновления данных
|
||
private async onDataUpdated() {
|
||
if (!EquipmentManager.instance) return;
|
||
|
||
// Получаем данные из EquipmentManager
|
||
const allData: apiSensors[] = await EquipmentManager.instance.getDataList();
|
||
|
||
// Получаем список имён из equipmentNode, для нод с компонентом MeshRenderer
|
||
const validNames: string[] = [];
|
||
if (this.equipmentNode) {
|
||
this.equipmentNode.children.forEach(child => {
|
||
if (child.getComponent(MeshRenderer)) {
|
||
validNames.push(child.name);
|
||
}
|
||
});
|
||
} else {
|
||
console.error("equipmentNode не задан!");
|
||
}
|
||
|
||
// Фильтруем данные, оставляя только элементы, имя которых есть в validNames
|
||
this._data = allData
|
||
.filter((item: apiSensors) => validNames.indexOf(item.name) !== -1)
|
||
|
||
.map(item => ({ ...item }));
|
||
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.itemPrefab);
|
||
const posY = - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1));
|
||
item.setPosition(0, posY, 0);
|
||
this._content.addChild(item);
|
||
|
||
const itemButton = item.getComponent(ItemButton);
|
||
if (itemButton) {
|
||
itemButton.initialize(this._data[i]);
|
||
itemButton.itemIndex = 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);
|
||
}
|
||
}
|
||
}
|
||
}
|