исправил проблему с мерцанием списка характеристик
и аварий перейдя на механизм виртуализации и использовав механизм отложенной загрузки
This commit is contained in:
parent
da9f2bfbf8
commit
4104adf0f7
@ -11,6 +11,11 @@ const { ccclass, property } = _decorator;
|
||||
@ccclass("ErrorLazyLoadList")
|
||||
export class ErrorLazyLoadList extends Component {
|
||||
public static instance: ErrorLazyLoadList | null = null;
|
||||
|
||||
// Статические поля для сохранения состояния между сценами
|
||||
private static _savedMode: "errors" | "details" = "errors";
|
||||
private static _savedSensorDescription: SensorDescription | null = null;
|
||||
private static _savedFilteredData: ErrorItemData[] | null = null;
|
||||
|
||||
@property(Prefab)
|
||||
public errorItemPrefab: Prefab = null!;
|
||||
@ -49,6 +54,7 @@ export class ErrorLazyLoadList extends Component {
|
||||
|
||||
// Active items tracking
|
||||
private _activeItems: Node[] = [];
|
||||
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
|
||||
private _firstVisibleIndex: number = 0;
|
||||
private _lastVisibleIndex: number = 0;
|
||||
|
||||
@ -73,13 +79,32 @@ export class ErrorLazyLoadList extends Component {
|
||||
this._itemHeight = tempUI!.height + this.spacing;
|
||||
tempNode.destroy();
|
||||
|
||||
this._mode = "errors";
|
||||
this.waitForErrorManager();
|
||||
// Восстанавливаем сохраненное состояние
|
||||
this._mode = ErrorLazyLoadList._savedMode;
|
||||
if (ErrorLazyLoadList._savedSensorDescription) {
|
||||
this._sensorDescription = ErrorLazyLoadList._savedSensorDescription;
|
||||
}
|
||||
this._filteredData = ErrorLazyLoadList._savedFilteredData;
|
||||
|
||||
// Устанавливаем правильный заголовок
|
||||
if (this._mode === "details" && this._sensorDescription) {
|
||||
this.header.string = `Детали ${this._sensorDescription.sensorName}`;
|
||||
} else if (this._filteredData) {
|
||||
this.header.string = `Аварии на ${this._filteredData[0]?.sensorName || "неизвестно"}`;
|
||||
} else {
|
||||
this.header.string = "Список всех аварий";
|
||||
}
|
||||
|
||||
this.waitForErrorManager();
|
||||
this.scrollView.node.on('scrolling', this.onScrolling, this);
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
// Сохраняем текущее состояние перед уничтожением
|
||||
ErrorLazyLoadList._savedMode = this._mode;
|
||||
ErrorLazyLoadList._savedSensorDescription = this._sensorDescription;
|
||||
ErrorLazyLoadList._savedFilteredData = this._filteredData;
|
||||
|
||||
// Clean up event listeners
|
||||
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
|
||||
|
||||
@ -144,7 +169,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
console.warn("Could not subscribe to ErrorManager events - node not found");
|
||||
}
|
||||
|
||||
this.onDataUpdated();
|
||||
// Обновляем отображение в зависимости от режима
|
||||
if (this._mode === "errors") {
|
||||
this.onDataUpdated();
|
||||
} else if (this._mode === "details") {
|
||||
// Для режима details обновляем размеры и элементы
|
||||
this.updateVisibleItems(true); // Принудительно обновляем (включая высоту)
|
||||
}
|
||||
}
|
||||
|
||||
private onDataUpdated() {
|
||||
@ -173,7 +204,6 @@ export class ErrorLazyLoadList extends Component {
|
||||
this._totalCount = this._data.length;
|
||||
}
|
||||
|
||||
this.updateContentHeight();
|
||||
this.updateVisibleItems();
|
||||
}
|
||||
|
||||
@ -181,7 +211,12 @@ export class ErrorLazyLoadList extends Component {
|
||||
this.updateVisibleItems();
|
||||
}
|
||||
|
||||
private updateVisibleItems() {
|
||||
private updateVisibleItems(forceUpdate: boolean = false) {
|
||||
// При принудительном обновлении всегда обновляем высоту контента
|
||||
if (forceUpdate) {
|
||||
this.updateContentHeight();
|
||||
}
|
||||
|
||||
const scrollY = this.scrollView.getScrollOffset().y;
|
||||
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||||
|
||||
@ -200,8 +235,9 @@ export class ErrorLazyLoadList extends Component {
|
||||
totalItems - 1
|
||||
);
|
||||
|
||||
// Always update if visible range changed
|
||||
const needsUpdate = newFirstVisible !== this._firstVisibleIndex ||
|
||||
// Always update if visible range changed OR if forced
|
||||
const needsUpdate = forceUpdate ||
|
||||
newFirstVisible !== this._firstVisibleIndex ||
|
||||
newLastVisible !== this._lastVisibleIndex;
|
||||
|
||||
if (!needsUpdate) {
|
||||
@ -220,6 +256,7 @@ export class ErrorLazyLoadList extends Component {
|
||||
this.returnItemToPool(item);
|
||||
}
|
||||
this._activeItems = [];
|
||||
this._activeItemsData = []; // Очищаем данные отслежи ания
|
||||
}
|
||||
|
||||
private returnItemToPool(item: Node) {
|
||||
@ -237,62 +274,122 @@ export class ErrorLazyLoadList extends Component {
|
||||
}
|
||||
|
||||
private updatePoolItems() {
|
||||
const itemsToShow = this._lastVisibleIndex - this._firstVisibleIndex + 1;
|
||||
const currentData = this.getCurrentData();
|
||||
|
||||
// Hide all current items first
|
||||
this.hideAllItems();
|
||||
|
||||
// Get the correct pool based on mode
|
||||
const itemsToShow = Math.min(
|
||||
this._lastVisibleIndex - this._firstVisibleIndex + 1,
|
||||
currentData.length - this._firstVisibleIndex
|
||||
);
|
||||
|
||||
// Определяем нужный пул для текущего режима
|
||||
let currentPool: NodePool;
|
||||
let expectedComponentType: string;
|
||||
|
||||
if (this._mode === "errors") {
|
||||
if (this._filteredData) {
|
||||
currentPool = this.getOrCreateNamedErrorItemPool();
|
||||
expectedComponentType = "ErrorItemNamedButton";
|
||||
} else {
|
||||
currentPool = this.getOrCreateErrorItemPool();
|
||||
expectedComponentType = "ErrorItemButton";
|
||||
}
|
||||
} else if (this._mode === "details") {
|
||||
currentPool = this.getOrCreateSensorFieldItemPool();
|
||||
expectedComponentType = "SensorFieldItem";
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Show and position visible items from the correct pool
|
||||
for (let i = 0; i < itemsToShow; i++) {
|
||||
// Проверяем совместимость существующих элементов с текущим режимом
|
||||
const incompatibleItems: Node[] = [];
|
||||
for (const item of this._activeItems) {
|
||||
const hasCorrectComponent = item.getComponent(expectedComponentType);
|
||||
if (!hasCorrectComponent) {
|
||||
incompatibleItems.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Убираем несовместимые элементы
|
||||
for (const item of incompatibleItems) {
|
||||
const index = this._activeItems.indexOf(item);
|
||||
if (index !== -1) {
|
||||
this._activeItems.splice(index, 1);
|
||||
this._activeItemsData.splice(index, 1); // Исправил: было pop(), должно быть splice()
|
||||
this.returnItemToPool(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Переиспользуем существующие элементы или создаем недостающие
|
||||
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() || this.createItemForCurrentMode();
|
||||
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 item = currentPool.get() || this.createItemForCurrentMode();
|
||||
if (!item) continue;
|
||||
const newData = currentData[dataIndex];
|
||||
const oldData = this._activeItemsData[i];
|
||||
|
||||
const component = this.getComponentForCurrentMode(item);
|
||||
// Сравниваем данные - обновляем только если изменились
|
||||
const needsUpdate = !oldData ||
|
||||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
|
||||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
|
||||
|
||||
// Position the item
|
||||
item.setPosition(0, -(dataIndex * this._itemHeight + this._itemHeight / 2 - this.spacing / 2), 0);
|
||||
|
||||
// Update item data
|
||||
try {
|
||||
switch (this._mode) {
|
||||
case "errors":
|
||||
if (component && 'initialize' in component && typeof component.initialize === 'function') {
|
||||
(component as ErrorItemButton | ErrorItemNamedButton).initialize(currentData[dataIndex]);
|
||||
}
|
||||
break;
|
||||
case "details":
|
||||
if (component && 'setData' in component && typeof component.setData === 'function') {
|
||||
(component as SensorFieldItem).setData(currentData[dataIndex]);
|
||||
}
|
||||
break;
|
||||
if (needsUpdate) {
|
||||
// Обновляем данные компонента
|
||||
const component = this.getComponentForCurrentMode(item);
|
||||
try {
|
||||
switch (this._mode) {
|
||||
case "errors":
|
||||
if (component && 'initialize' in component && typeof component.initialize === 'function') {
|
||||
(component as ErrorItemButton | ErrorItemNamedButton).initialize(newData);
|
||||
}
|
||||
break;
|
||||
case "details":
|
||||
if (component && 'setData' in component && typeof component.setData === 'function') {
|
||||
(component as SensorFieldItem).setData(newData);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Сохраняем новые данные для будущих сравнений
|
||||
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
|
||||
} catch (e) {
|
||||
console.warn("Error updating item component:", e);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error updating item component:", e);
|
||||
}
|
||||
|
||||
// Show the item and add to content
|
||||
this._content.addChild(item);
|
||||
item.active = true;
|
||||
this._activeItems.push(item);
|
||||
// Позиционируем элемент (это нужно делать всегда для виртуализации)
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -355,18 +452,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
*/
|
||||
public filterBySensor(sensorName: string) {
|
||||
this.preserveScrollPosition(() => {
|
||||
this.hideAllItems();
|
||||
|
||||
this._mode = "errors";
|
||||
this.header.string = `Аварии на ${sensorName}`;
|
||||
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
|
||||
this._totalCount = this._filteredData.length;
|
||||
|
||||
this.updateContentHeight();
|
||||
this._firstVisibleIndex = 0;
|
||||
this._lastVisibleIndex = 0;
|
||||
|
||||
this.updatePoolItems();
|
||||
// Принудительно обновляем данные
|
||||
this.updateVisibleItems(true);
|
||||
});
|
||||
}
|
||||
|
||||
@ -375,18 +467,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
*/
|
||||
public resetFilter() {
|
||||
this.preserveScrollPosition(() => {
|
||||
this.hideAllItems();
|
||||
|
||||
this.header.string = "Список всех аварий";
|
||||
this._mode = "errors";
|
||||
this._filteredData = null;
|
||||
this._totalCount = this._data.length;
|
||||
|
||||
this.updateContentHeight();
|
||||
this._firstVisibleIndex = 0;
|
||||
this._lastVisibleIndex = 0;
|
||||
|
||||
this.updatePoolItems();
|
||||
// Принудительно обновляем данные
|
||||
this.updateVisibleItems(true);
|
||||
});
|
||||
}
|
||||
|
||||
@ -396,8 +483,6 @@ export class ErrorLazyLoadList extends Component {
|
||||
*/
|
||||
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
|
||||
this.preserveScrollPosition(() => {
|
||||
this.hideAllItems();
|
||||
|
||||
this._mode = "details";
|
||||
this.header.string = `Детали ${data.sensorName}`;
|
||||
this._sensorDescription = {
|
||||
@ -405,11 +490,8 @@ export class ErrorLazyLoadList extends Component {
|
||||
fields: data.fields || []
|
||||
};
|
||||
|
||||
this.updateContentHeight();
|
||||
this._firstVisibleIndex = 0;
|
||||
this._lastVisibleIndex = 0;
|
||||
|
||||
this.updatePoolItems();
|
||||
// Принудительно обновляем данные
|
||||
this.updateVisibleItems(true);
|
||||
});
|
||||
}
|
||||
|
||||
@ -418,18 +500,13 @@ export class ErrorLazyLoadList extends Component {
|
||||
*/
|
||||
public showErrors() {
|
||||
this.preserveScrollPosition(() => {
|
||||
this.hideAllItems();
|
||||
|
||||
this._mode = "errors";
|
||||
this.header.string = "Список всех аварий";
|
||||
this._filteredData = null;
|
||||
this._totalCount = this._data.length;
|
||||
|
||||
this.updateContentHeight();
|
||||
this._firstVisibleIndex = 0;
|
||||
this._lastVisibleIndex = 0;
|
||||
|
||||
this.updatePoolItems();
|
||||
// Принудительно обновляем данные
|
||||
this.updateVisibleItems(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -9,7 +9,7 @@ export class MorphButtonWithButton extends Component {
|
||||
|
||||
@property(Sprite) targetSprite!: Sprite;
|
||||
|
||||
private isQuestion = true;
|
||||
private isQuestion = false;
|
||||
|
||||
onLoad() {
|
||||
this.targetSprite.spriteFrame = this.questionFrame;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user