(высота списка теперь корректно обновляется при изменении количества ошибок)
270 lines
10 KiB
TypeScript
270 lines
10 KiB
TypeScript
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, MeshRenderer, NodePool } 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!;
|
||
|
||
@property(Node)
|
||
public equipmentNode: Node = null!;
|
||
|
||
@property
|
||
public spacing: number = 10;
|
||
|
||
@property
|
||
public visibleItemCount: number = 15; // Visible items buffer size
|
||
|
||
private _data: apiSensors[] = [];
|
||
private _totalCount: number = 0;
|
||
private _itemHeight: number = 0; // Including spacing
|
||
private _content: Node = null!;
|
||
private _contentUI: UITransform = null!;
|
||
|
||
// Pool for item reuse
|
||
private _itemPool: NodePool | null = null;
|
||
|
||
// Active items tracking
|
||
private _activeItems: Node[] = [];
|
||
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
|
||
private _firstVisibleIndex: number = 0;
|
||
private _lastVisibleIndex: number = 0;
|
||
|
||
onLoad() {
|
||
if (!this.scrollView.content) {
|
||
console.error("ScrollView.content равен null!");
|
||
return;
|
||
}
|
||
this._content = this.scrollView.content;
|
||
this._contentUI = this._content.getComponent(UITransform)!;
|
||
|
||
// Calculate item height including spacing
|
||
const tempNode: Node = instantiate(this.itemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
if (!tempUI) {
|
||
console.error("В префабе отсутствует компонент UITransform!");
|
||
tempNode.destroy();
|
||
return;
|
||
}
|
||
this._itemHeight = tempUI.height + this.spacing;
|
||
tempNode.destroy();
|
||
|
||
this.waitForEquipmentManager();
|
||
|
||
// Добавляем обработчик прокрутки для виртуализации
|
||
this.scrollView.node.on('scrolling', this.onScrolling, this);
|
||
}
|
||
|
||
private getOrCreateItemPool(): NodePool {
|
||
if (!this._itemPool) {
|
||
this._itemPool = new NodePool();
|
||
for (let i = 0; i < this.visibleItemCount; i++) {
|
||
this._itemPool.put(instantiate(this.itemPrefab));
|
||
}
|
||
}
|
||
return this._itemPool;
|
||
}
|
||
|
||
private onScrolling() {
|
||
this.updateVisibleItems();
|
||
}
|
||
|
||
private waitForEquipmentManager() {
|
||
if (!EquipmentManager.instance) {
|
||
this.scheduleOnce(() => { this.waitForEquipmentManager(); }, 0.1);
|
||
return;
|
||
}
|
||
|
||
EquipmentManager.instance.initialDataPromise.then(() => {
|
||
EquipmentManager.instance.node.on('data-updated', this.onDataUpdated, this);
|
||
this.onDataUpdated();
|
||
}).catch((error) => {
|
||
console.error("Ошибка загрузки данных в EquipmentManager:", error);
|
||
});
|
||
}
|
||
|
||
private async onDataUpdated() {
|
||
if (!EquipmentManager.instance) return;
|
||
|
||
const allData: apiSensors[] = await EquipmentManager.instance.getDataList();
|
||
const validNames: string[] = [];
|
||
|
||
if (this.equipmentNode) {
|
||
this.equipmentNode.children.forEach(child => {
|
||
if (child.getComponent(MeshRenderer)) {
|
||
validNames.push(child.name);
|
||
}
|
||
});
|
||
}
|
||
|
||
this._data = allData.filter(item => validNames.indexOf(item.name) !== -1);
|
||
this._totalCount = this._data.length;
|
||
|
||
// Очищаем активные элементы
|
||
this.hideAllItems();
|
||
|
||
// Обновляем видимые элементы
|
||
this.updateVisibleItems(true);
|
||
}
|
||
|
||
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._totalCount;
|
||
|
||
// 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 pool
|
||
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();
|
||
this.getOrCreateItemPool().put(item);
|
||
}
|
||
|
||
private updatePoolItems() {
|
||
const currentData = this._data;
|
||
const itemsToShow = Math.min(
|
||
this._lastVisibleIndex - this._firstVisibleIndex + 1,
|
||
currentData.length - this._firstVisibleIndex
|
||
);
|
||
|
||
const currentPool = this.getOrCreateItemPool();
|
||
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 = currentPool.get() || instantiate(this.itemPrefab);
|
||
|
||
if (!item) break;
|
||
|
||
this._content.addChild(item);
|
||
item.active = true;
|
||
this._activeItems.push(item);
|
||
this._activeItemsData.push(null); // Placeholder для новых элементов
|
||
}
|
||
|
||
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
|
||
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 isNewItem = !oldData;
|
||
const needsUpdate = isNewItem ||
|
||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
|
||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
|
||
|
||
if (needsUpdate) {
|
||
// Обновляем данные компонента
|
||
const component = item.getComponent(ItemButton);
|
||
if (component) {
|
||
if (isNewItem) {
|
||
// Для новых элементов используем полную инициализацию
|
||
component.initialize(newData);
|
||
} else {
|
||
// Для существующих элементов используем обновление данных
|
||
component.updateData(newData);
|
||
}
|
||
component.itemIndex = dataIndex;
|
||
}
|
||
|
||
// Сохраняем новые данные для будущих сравнений
|
||
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
|
||
}
|
||
|
||
// Позиционируем элемент (это нужно делать всегда для виртуализации)
|
||
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 updateContentHeight() {
|
||
this._contentUI.height = this._totalCount * this._itemHeight;
|
||
}
|
||
|
||
onDestroy() {
|
||
// Безопасно отписываемся от обновлений данных
|
||
EquipmentManager.instance?.node?.off('data-updated', this.onDataUpdated, this);
|
||
// Отписываемся от скроллинга, только если scrollView и его node ещё существуют
|
||
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
|
||
|
||
// Очищаем пул и активные элементы
|
||
this._itemPool?.clear();
|
||
this._activeItems = [];
|
||
this._activeItemsData = [];
|
||
}
|
||
}
|