отрисовка префаба в левом списке теперь происходит корректно
(высота списка теперь корректно обновляется при изменении количества ошибок)
This commit is contained in:
parent
adbf4faed0
commit
3e15603f17
@ -1032,6 +1032,7 @@
|
||||
"__id__": 0
|
||||
},
|
||||
"fileId": "4aBpvR+bhJdI7i8LzRRtvb",
|
||||
"instance": null
|
||||
"instance": null,
|
||||
"targetOverrides": null
|
||||
}
|
||||
]
|
||||
@ -13919,6 +13919,7 @@
|
||||
"__id__": 34
|
||||
},
|
||||
"spacing": 10,
|
||||
"visibleItemCount": 15,
|
||||
"_id": "02Z+hMjflI57Ua6GmQMDOg"
|
||||
},
|
||||
{
|
||||
|
||||
@ -237,6 +237,7 @@ export class ErrorLazyLoadList extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
const oldDataLength = this._data.length;
|
||||
this._data = flattened;
|
||||
|
||||
// Update both filtered and unfiltered views
|
||||
@ -244,11 +245,24 @@ export class ErrorLazyLoadList extends Component {
|
||||
// If we have a filter, reapply it to the new data
|
||||
const currentFilter = this._filteredData.length > 0 ? this._filteredData[0].sensorName : '';
|
||||
if (currentFilter) {
|
||||
const oldFilteredLength = this._filteredData.length;
|
||||
this._filteredData = this._data.filter(item => item.sensorName === currentFilter);
|
||||
this._totalCount = this._filteredData.length;
|
||||
|
||||
// Принудительно обновляем высоту если изменилось количество отфильтрованных элементов
|
||||
if (oldFilteredLength !== this._filteredData.length) {
|
||||
this.updateVisibleItems(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this._totalCount = this._data.length;
|
||||
|
||||
// Принудительно обновляем высоту если изменилось общее количество элементов
|
||||
if (oldDataLength !== this._data.length) {
|
||||
this.updateVisibleItems(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Просто обновляем видимые элементы без уничтожения
|
||||
@ -260,8 +274,12 @@ export class ErrorLazyLoadList extends Component {
|
||||
}
|
||||
|
||||
private updateVisibleItems(forceUpdate: boolean = false) {
|
||||
const totalItems = this.getTotalItems();
|
||||
|
||||
// При принудительном обновлении всегда обновляем высоту контента
|
||||
if (forceUpdate) {
|
||||
// Также обновляем высоту если изменилось общее количество элементов
|
||||
if (forceUpdate || this._totalCount !== totalItems) {
|
||||
this._totalCount = totalItems;
|
||||
this.updateContentHeight();
|
||||
}
|
||||
|
||||
@ -270,7 +288,6 @@ export class ErrorLazyLoadList extends Component {
|
||||
|
||||
// Calculate the first visible item index based on scroll position
|
||||
const newFirstVisible = Math.floor(Math.max(0, scrollY) / this._itemHeight);
|
||||
const totalItems = this.getTotalItems();
|
||||
|
||||
// Handle the case when there are no items
|
||||
if (totalItems <= 0) {
|
||||
@ -559,7 +576,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
|
||||
private updateContentHeight() {
|
||||
const totalItems = this.getTotalItems();
|
||||
this._contentUI.height = totalItems * this._itemHeight;
|
||||
const newHeight = totalItems * this._itemHeight;
|
||||
const oldHeight = this._contentUI.height;
|
||||
|
||||
if (oldHeight !== newHeight) {
|
||||
console.log(`[ErrorLazyLoadList] Updating content height: ${oldHeight} -> ${newHeight} (items: ${totalItems})`);
|
||||
this._contentUI.height = newHeight;
|
||||
}
|
||||
}
|
||||
|
||||
private preserveScrollPosition(callback: () => void) {
|
||||
@ -662,6 +685,10 @@ export class ErrorLazyLoadList extends Component {
|
||||
|
||||
console.log(`[ErrorLazyLoadList] updateSensorDetails: ${data.sensorName}, fields count: ${data.fields?.length || 0}`);
|
||||
|
||||
// Сохраняем старое количество полей для сравнения
|
||||
const oldFieldsCount = this._sensorDescription.fields?.length || 0;
|
||||
const newFieldsCount = data.fields?.length || 0;
|
||||
|
||||
// Обновляем данные
|
||||
this._sensorDescription = {
|
||||
sensorName: data.sensorName,
|
||||
@ -674,8 +701,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
// Принудительно обновляем все активные элементы датчика
|
||||
this.forceUpdateActiveSensorItems(data.sensorName, data.fields);
|
||||
|
||||
// Обновляем видимые элементы с принудительным обновлением данных
|
||||
this.updateVisibleItems(false);
|
||||
// Если изменилось количество полей, принудительно обновляем высоту контента
|
||||
if (oldFieldsCount !== newFieldsCount) {
|
||||
this.updateVisibleItems(true);
|
||||
} else {
|
||||
// Обновляем видимые элементы без принудительного обновления высоты
|
||||
this.updateVisibleItems(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, MeshRenderer } from 'cc';
|
||||
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';
|
||||
@ -19,12 +19,23 @@ export class LazyLoadList extends Component {
|
||||
@property
|
||||
public spacing: number = 10;
|
||||
|
||||
@property
|
||||
public visibleItemCount: number = 15; // Visible items buffer size
|
||||
|
||||
private _data: apiSensors[] = [];
|
||||
private _totalCount: number = 0;
|
||||
private _loadedCount: number = 0;
|
||||
private _itemHeight: 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) {
|
||||
@ -34,6 +45,7 @@ export class LazyLoadList extends Component {
|
||||
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) {
|
||||
@ -41,23 +53,27 @@ export class LazyLoadList extends Component {
|
||||
tempNode.destroy();
|
||||
return;
|
||||
}
|
||||
this._itemHeight = tempUI.height;
|
||||
this._itemHeight = tempUI.height + this.spacing;
|
||||
tempNode.destroy();
|
||||
|
||||
this.waitForEquipmentManager();
|
||||
|
||||
// Добавляем обработчик прокрутки по аналогии с рабочим компонентом
|
||||
// Добавляем обработчик прокрутки для виртуализации
|
||||
this.scrollView.node.on('scrolling', this.onScrolling, this);
|
||||
}
|
||||
|
||||
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 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() {
|
||||
@ -91,35 +107,152 @@ export class LazyLoadList extends Component {
|
||||
this._data = allData.filter(item => validNames.indexOf(item.name) !== -1);
|
||||
this._totalCount = this._data.length;
|
||||
|
||||
this._loadedCount = 0;
|
||||
this._content.removeAllChildren();
|
||||
this.loadNextBatch(20);
|
||||
// Очищаем активные элементы
|
||||
this.hideAllItems();
|
||||
|
||||
// Обновляем видимые элементы
|
||||
this.updateVisibleItems(true);
|
||||
}
|
||||
|
||||
loadNextBatch(batchSize: number) {
|
||||
if (this._loadedCount >= this._totalCount) return;
|
||||
|
||||
const endIndex = Math.min(this._loadedCount + batchSize, this._totalCount);
|
||||
private updateVisibleItems(forceUpdate: boolean = false) {
|
||||
// При принудительном обновлении всегда обновляем высоту контента
|
||||
if (forceUpdate) {
|
||||
this.updateContentHeight();
|
||||
}
|
||||
|
||||
for (let i = this._loadedCount; i < endIndex; i++) {
|
||||
const item: Node = instantiate(this.itemPrefab);
|
||||
const scrollY = this.scrollView.getScrollOffset().y;
|
||||
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||||
|
||||
const posY = -(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2);
|
||||
item.setPosition(0, posY, 0);
|
||||
this._content.addChild(item);
|
||||
// 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
|
||||
);
|
||||
|
||||
const itemButton = item.getComponent(ItemButton);
|
||||
if (itemButton) {
|
||||
itemButton.initialize(this._data[i]);
|
||||
itemButton.itemIndex = i;
|
||||
} else {
|
||||
console.error("Компонент ItemButton не найден на ноде", item);
|
||||
}
|
||||
// Always update if visible range changed OR if forced
|
||||
const needsUpdate = forceUpdate ||
|
||||
newFirstVisible !== this._firstVisibleIndex ||
|
||||
newLastVisible !== this._lastVisibleIndex;
|
||||
|
||||
this._loadedCount++;
|
||||
if (!needsUpdate) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
|
||||
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() {
|
||||
@ -127,5 +260,10 @@ export class LazyLoadList extends Component {
|
||||
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 = [];
|
||||
}
|
||||
}
|
||||
|
||||
@ -45,10 +45,28 @@ export class ItemButton extends Component {
|
||||
this.itemData = data;
|
||||
if (this.nameLabel) {
|
||||
this.nameLabel.string = data.name;
|
||||
// Изначально скрываем кнопку ошибок
|
||||
this.ErrorButton.node.active = false;
|
||||
}
|
||||
// Дополнительная логика, если требуется
|
||||
|
||||
// Обновляем состояние ошибок без мерцания
|
||||
this.updateErrorStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновляет только данные элемента без полной переинициализации
|
||||
*/
|
||||
public updateData(data: apiSensors) {
|
||||
// Проверяем, действительно ли данные изменились
|
||||
if (this.itemData && this.itemData.name === data.name && this.itemData.value === data.value) {
|
||||
return; // Данные не изменились, не обновляем
|
||||
}
|
||||
|
||||
this.itemData = data;
|
||||
if (this.nameLabel && this.nameLabel.string !== data.name) {
|
||||
this.nameLabel.string = data.name;
|
||||
}
|
||||
|
||||
// Обновляем состояние ошибок только если данные действительно изменились
|
||||
this.updateErrorStatus();
|
||||
}
|
||||
|
||||
onLoad() {
|
||||
@ -209,16 +227,20 @@ export class ItemButton extends Component {
|
||||
* Обновление состояния ошибки на кнопке в зависимости от данных оборудования.
|
||||
*/
|
||||
private updateErrorStatus() {
|
||||
if (!this.itemData || !EquipmentManager.instance || !ErrorManager.instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sensors = EquipmentManager.instance.dataList;
|
||||
const sensorData = sensors.find((s) => s.name === this.itemData.name);
|
||||
if (!sensorData) {
|
||||
this.ErrorButton.node.active = false;
|
||||
this.setErrorButtonState(false, "0");
|
||||
return;
|
||||
}
|
||||
|
||||
// Если датчик активен – скрываем кнопку ошибок
|
||||
if (sensorData.value === SensorStatus.Active) {
|
||||
this.ErrorButton.node.active = false;
|
||||
this.setErrorButtonState(false, "0");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -232,10 +254,26 @@ export class ItemButton extends Component {
|
||||
|
||||
// Если есть хотя бы одна ошибка, отображаем кнопку с количеством ошибок
|
||||
if (errorCount > 0) {
|
||||
this.ErrorButton.node.active = true;
|
||||
this.ErrorNumber.string = errorCount.toString();
|
||||
this.setErrorButtonState(true, errorCount.toString());
|
||||
} else {
|
||||
this.ErrorButton.node.active = false;
|
||||
this.setErrorButtonState(false, "0");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает состояние кнопки ошибок только если оно изменилось
|
||||
*/
|
||||
private setErrorButtonState(isVisible: boolean, errorText: string) {
|
||||
if (!this.ErrorButton || !this.ErrorNumber) return;
|
||||
|
||||
// Обновляем видимость только если она изменилась
|
||||
if (this.ErrorButton.node.active !== isVisible) {
|
||||
this.ErrorButton.node.active = isVisible;
|
||||
}
|
||||
|
||||
// Обновляем текст только если он изменился
|
||||
if (this.ErrorNumber.string !== errorText) {
|
||||
this.ErrorNumber.string = errorText;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user