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

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

View File

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