избавился от дерготни перерисовки списка

This commit is contained in:
Georgy Shive 2025-04-09 14:14:47 +07:00
parent d956f3d413
commit 5bc2daaee5
2 changed files with 49 additions and 79 deletions

View File

@ -6161,7 +6161,7 @@
"_priority": 1073741824,
"_fov": 45,
"_fovAxis": 0,
"_orthoHeight": 360,
"_orthoHeight": 381.2971342383107,
"_near": 1,
"_far": 2000,
"_color": {
@ -11307,7 +11307,7 @@
"_string": "Список всех аварий",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 14,
"_actualFontSize": 16,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 30,
@ -11901,7 +11901,7 @@
"_string": "button",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 26.166666666666668,
"_actualFontSize": 36.2578125,
"_fontSize": 20,
"_fontFamily": "Arial",
"_lineHeight": 40,
@ -12475,7 +12475,7 @@
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 131.30711257837382,
"width": 131.29982762335703,
"height": 25.2
},
"_anchorPoint": {
@ -12508,7 +12508,7 @@
"_string": "ScrollView content",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 20.933333333333334,
"_actualFontSize": 29.00625,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 20,

View File

@ -10,13 +10,11 @@ const { ccclass, property } = _decorator;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
// Синглтон для доступа из других мест
public static instance: ErrorLazyLoadList | null = null;
@property(Prefab)
public errorItemPrefab: Prefab = null!;
// Префаб, который будет использоваться для отрисовки деталей датчика
@property(Prefab)
public sensorFieldItemPrefab: Prefab = null!;
@ -32,59 +30,50 @@ export class ErrorLazyLoadList extends Component {
@property(Label)
public header: Label = null!;
// Массив для хранения всех ошибок, полученных с API (плоский список)
private _data: ErrorItemData[] = [];
// Массив для хранения отфильтрованных данных (если фильтр активирован)
private _filteredData: ErrorItemData[] | null = null;
// Дополнительно: режим отображения – ошибки или детали
private _mode: "errors" | "details" = "errors";
// Данные описания датчика (SensorDescription) для режима "details"
private _sensorDescription: SensorDescription = null!;
private _totalCount: number = 0;
private _loadedCount: number = 0;
private _itemHeight: number = 0;
private _content: Node = null!;
private _contentUI: UITransform = null!;
/**
* для получения сведений о текущем режиме отображения
*/
public get mode(): "errors" | "details" {
return this._mode;
}
onLoad() {
// Назначаем синглтон
ErrorLazyLoadList.instance = this;
if (!this.scrollView.content) {
console.error("ScrollView.content is null!");
return;
}
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
if (!this._contentUI) {
console.error("Content node does not have UITransform component!");
return;
}
// Определяем высоту элемента через префаб (используем errorItemPrefab)
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (!tempUI) {
console.error("Prefab missing UITransform component!");
tempNode.destroy();
return;
}
this._itemHeight = tempUI.height;
this._itemHeight = tempUI!.height;
tempNode.destroy();
// Изначально работаем в режиме "errors"
this._mode = "errors";
this.waitForErrorManager();
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);
}
}
onDestroy() {
@ -93,9 +82,8 @@ export class ErrorLazyLoadList extends Component {
}
}
private waitForErrorManager() {
private waitForErrorManager() {
if (!ErrorManager.instance) {
console.warn("ErrorManager.instance not found, retrying...");
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
return;
}
@ -103,19 +91,14 @@ export class ErrorLazyLoadList extends Component {
this.onDataUpdated();
}
private onDataUpdated() {
// Обновляем данные только в режиме ошибок
if (this._mode !== "errors") return;
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
const flattened: ErrorItemData[] = [];
for (const sensorName in apiErrors) {
for (const err of apiErrors[sensorName]) {
flattened.push({
sensorName,
alarmCode: err.alarmCode,
description: err.description,
timestamp: err.timestamp
});
flattened.push({ sensorName, alarmCode: err.alarmCode, description: err.description, timestamp: err.timestamp });
}
}
this._data = flattened;
@ -127,57 +110,44 @@ export class ErrorLazyLoadList extends Component {
}
}
loadNextBatch(batchSize: number) {
private loadNextBatch(batchSize: number) {
let currentData: any[] = [];
if (this._mode === "errors") {
currentData = this._filteredData || this._data;
} else if (this._mode === "details") {
currentData = this._sensorDescription ? this._sensorDescription.fields : [];
currentData = this._sensorDescription?.fields || [];
}
if (this._loadedCount >= currentData.length) return;
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
for (let i = this._loadedCount; i < endIndex; i++) {
let item: Node;
if (this._mode === "errors") {
if (this._filteredData) {
item = instantiate(this.errorItemNamedPrefab);
const errorItemNamedButton = item.getComponent("ErrorItemNamedButton") as unknown as ErrorItemNamedButton;
if (errorItemNamedButton) {
errorItemNamedButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemNamedButton не найден на префабе.");
}
} else {
item = instantiate(this.errorItemPrefab);
const errorItemButton = item.getComponent("ErrorItemButton") as unknown as ErrorItemButton;
if (errorItemButton) {
errorItemButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemButton не найден на префабе.");
}
}
} else if (this._mode === "details") {
item = instantiate(this.sensorFieldItemPrefab);
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
sensorFieldItem.setData(currentData[i]);
} else {
console.warn("Компонент SensorFieldItem не найден на префабе.");
}
} else {
console.error("Неизвестный режим: " + this._mode);
continue;
switch (this._mode) {
case "errors":
item = instantiate(this._filteredData ? this.errorItemNamedPrefab : this.errorItemPrefab);
const componentName = this._filteredData ? "ErrorItemNamedButton" : "ErrorItemButton";
const errorItem = item.getComponent(componentName) as unknown as ErrorItemNamedButton | ErrorItemButton;
errorItem?.initialize(currentData[i]);
break;
case "details":
item = instantiate(this.sensorFieldItemPrefab);
const sensorFieldItem = item.getComponent(SensorFieldItem);
sensorFieldItem?.setData(currentData[i]);
break;
default:
continue;
}
// Пока просто добавляем элемент, без позиционирования
item.setPosition(0, -(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2), 0);
this._content.addChild(item);
this._loadedCount++;
}
this._loadedCount = endIndex;
// После добавления новой партии элементов, переспозиционируем всех дочерних
this.scheduleOnce(() => {
this.repositionChildren();
}, 0);
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
}