избавил от подгрузки по чанкам и перешел на

отрисовку из пула, теперь поведение элементов
 с подсказкой уже лучше, осталось ввести по элементный
 пул .
This commit is contained in:
Georgy Shive 2025-05-24 04:22:26 +07:00
parent 6a5ba19e3d
commit 1d81901b6a
2 changed files with 423 additions and 196 deletions

View File

@ -6161,7 +6161,7 @@
"_priority": 1073741824,
"_fov": 45,
"_fovAxis": 0,
"_orthoHeight": 420.418410041841,
"_orthoHeight": 364.88687782805425,
"_near": 1,
"_far": 2000,
"_color": {
@ -6411,7 +6411,7 @@
"_string": "Список оборудования",
"_horizontalAlign": 0,
"_verticalAlign": 1,
"_actualFontSize": 18,
"_actualFontSize": 30,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 20,
@ -10891,7 +10891,7 @@
"_string": "button",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 22.40625,
"_actualFontSize": 36.2578125,
"_fontSize": 20,
"_fontFamily": "Arial",
"_lineHeight": 40,
@ -11865,7 +11865,7 @@
"_string": "Список всех аварий",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 12,
"_actualFontSize": 20,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 30,
@ -12221,7 +12221,7 @@
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 131.2914324006276,
"width": 131.29982762335703,
"height": 25.2
},
"_anchorPoint": {
@ -12254,7 +12254,7 @@
"_string": "ScrollView content",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 17.925,
"_actualFontSize": 29.00625,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 20,
@ -12567,21 +12567,22 @@
"__uuid__": "d793baca-b1ac-4011-9deb-b25ad00aab6d",
"__expectedType__": "cc.Prefab"
},
"errorItemNamedPrefab": {
"__uuid__": "39b13132-9edb-47b6-af69-148bb4ae9b2f",
"__expectedType__": "cc.Prefab"
},
"sensorFieldItemPrefab": {
"__uuid__": "53ae830a-e22f-4c8c-b5fd-f4e39ddabc5f",
"__expectedType__": "cc.Prefab"
},
"errorItemNamedPrefab": {
"__uuid__": "39b13132-9edb-47b6-af69-148bb4ae9b2f",
"__expectedType__": "cc.Prefab"
},
"scrollView": {
"__id__": 329
},
"spacing": 10,
"header": {
"__id__": 335
},
"spacing": 10,
"visibleItemCount": 15,
"_id": "21wy+/2mRJFqMMSBRnfwOL"
},
{

View File

@ -1,209 +1,435 @@
// scripts/ui/ErrorLazyLoadList.ts
import {
_decorator,
Component,
Prefab,
ScrollView,
instantiate,
UITransform,
Node,
Label,
director
} from 'cc';
import { ErrorItemData } from '../stores/ErrorItemData';
import { ErrorManager } from '../stores/ErrorManager';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
import { SensorDescriptionField } from '../stores/SensorDescriptionField';
import { SensorFieldItem } from './SensorFieldItem';
const { ccclass, property } = _decorator;
@ccclass('ErrorLazyLoadList')
export class ErrorLazyLoadList extends Component {
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, Label, NodePool, Vec3 } from 'cc';
import { ErrorItemData } from '../stores/ErrorItemData';
import { ErrorManager } from '../stores/ErrorManager';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
import { SensorDescription } from '../stores/SensorDescriptionField';
import { SensorFieldItem } from './SensorFieldItem';
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 errorItemNamedPrefab: Prefab = null!;
@property(Prefab) public sensorFieldItemPrefab: Prefab = null!;
@property(ScrollView) public scrollView: ScrollView = null!;
@property(Label) public header: Label = null!;
@property spacing = 10;
@property(Prefab)
public errorItemPrefab: Prefab = null!;
@property(Prefab)
public sensorFieldItemPrefab: Prefab = null!;
@property(Prefab)
public errorItemNamedPrefab: Prefab = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
@property
public spacing: number = 10;
@property(Label)
public header: Label = null!;
@property
public visibleItemCount: number = 15; // Visible items buffer size
private _data: ErrorItemData[] = [];
private _filteredData: ErrorItemData[] | null = null;
private _mode: 'errors' | 'details' = 'errors';
private _sensorDescription!: { sensorName: string; fields: SensorDescriptionField[] };
private _itemHeight = 0;
private _loadedCount = 0;
private _content!: Node;
private _contentUI!: UITransform;
public get mode() {
return this._mode;
private _mode: "errors" | "details" = "errors";
private _sensorDescription: SensorDescription = null!;
private _totalCount: number = 0;
private _itemHeight: number = 0; // Including spacing
private _content: Node = null!;
private _contentUI: UITransform = null!;
// Lazy-created NodePools
private _errorItemPool: NodePool | null = null;
private _namedErrorItemPool: NodePool | null = null;
private _sensorFieldItemPool: NodePool | null = null;
// Active items tracking
private _activeItems: Node[] = [];
private _firstVisibleIndex: number = 0;
private _lastVisibleIndex: number = 0;
public get mode(): "errors" | "details" {
return this._mode;
}
onLoad() {
ErrorLazyLoadList.instance = this;
director.addPersistRootNode(this.node);
if (!this.scrollView.content) {
console.error('ScrollView.content is null!');
return;
}
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
// Вычисляем высоту элемента
const tmp = instantiate(this.errorItemPrefab);
const tmpUI = tmp.getComponent(UITransform);
this._itemHeight = tmpUI ? tmpUI.height : 0;
tmp.destroy();
// Сбрасываем фильтр и заголовок
this._filteredData = null;
this._mode = 'errors';
this.header.string = 'Список всех аварий';
this.waitForErrorManager();
this.scrollView.node.on('scrolling', this.onScrolling, this);
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)!;
// Calculate item height including spacing
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
this._itemHeight = tempUI!.height + this.spacing;
tempNode.destroy();
this._mode = "errors";
this.waitForErrorManager();
this.scrollView.node.on('scrolling', this.onScrolling, this);
}
onDestroy() {
// Сбрасываем статический экземпляр, если он указывает на этот компонент
// Clean up event listeners
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
const errorManagerNode = (ErrorManager.instance as any)?.node;
if (errorManagerNode) {
errorManagerNode.off('errors-updated', this.onDataUpdated, this);
}
// Clear pools
this._errorItemPool?.clear();
this._namedErrorItemPool?.clear();
this._sensorFieldItemPool?.clear();
if (ErrorLazyLoadList.instance === this) {
ErrorLazyLoadList.instance = null;
}
// Убираем подписку на обновления ошибок
ErrorManager.instance?.node?.off('errors-updated', this.onDataUpdated, this);
// Безопасно отписываемся от скроллинга (если scrollView или его node уже уничтожены, ничего не произойдёт)
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
// Если нужно убрать persistence:
// director.removePersistRootNode(this.node);
}
private getOrCreateErrorItemPool(): NodePool {
if (!this._errorItemPool) {
this._errorItemPool = new NodePool();
for (let i = 0; i < this.visibleItemCount; i++) {
this._errorItemPool.put(instantiate(this.errorItemPrefab));
}
}
return this._errorItemPool;
}
private getOrCreateNamedErrorItemPool(): NodePool {
if (!this._namedErrorItemPool) {
this._namedErrorItemPool = new NodePool();
for (let i = 0; i < this.visibleItemCount; i++) {
this._namedErrorItemPool.put(instantiate(this.errorItemNamedPrefab));
}
}
return this._namedErrorItemPool;
}
private getOrCreateSensorFieldItemPool(): NodePool {
if (!this._sensorFieldItemPool) {
this._sensorFieldItemPool = new NodePool();
// For sensor fields, we might need more items depending on the sensor
const poolSize = Math.max(this.visibleItemCount, 20); // At least 20 for complex sensors
for (let i = 0; i < poolSize; i++) {
this._sensorFieldItemPool.put(instantiate(this.sensorFieldItemPrefab));
}
}
return this._sensorFieldItemPool;
}
private waitForErrorManager() {
if (!ErrorManager.instance) {
this.scheduleOnce(() => this.waitForErrorManager(), 0.1);
return;
}
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
this.onDataUpdated();
}
private onDataUpdated() {
if (this._mode !== 'errors') return;
// Собираем все ошибки из API
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
const flat: ErrorItemData[] = [];
for (const sensorName in apiErrors) {
for (const err of apiErrors[sensorName]) {
flat.push({
sensorName,
alarmCode: err.alarmCode,
description: err.description,
timestamp: err.timestamp,
});
if (!ErrorManager.instance) {
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
return;
}
}
this._data = flat;
// Полная перерисовка списка
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
private onScrolling() {
const offsetY = this.scrollView.getScrollOffset().y;
const viewH = this.scrollView.node.getComponent(UITransform)!.height;
const contentH = this._contentUI.height;
if (offsetY + viewH + this._itemHeight * 2 >= contentH) {
this.loadNextBatch(20);
}
}
private loadNextBatch(batchSize: number) {
// Определяем источник данных
const source = this._mode === 'errors'
? (this._filteredData || this._data)
: this._sensorDescription.fields;
if (this._loadedCount >= source.length) return;
const end = Math.min(this._loadedCount + batchSize, source.length);
for (let i = this._loadedCount; i < end; i++) {
const itemData = source[i];
let node: Node;
if (this._mode === 'errors') {
// Ошибки
const data = itemData as ErrorItemData;
if (this._filteredData) {
node = instantiate(this.errorItemNamedPrefab);
node.getComponent(ErrorItemNamedButton)?.initialize(data);
} else {
node = instantiate(this.errorItemPrefab);
node.getComponent(ErrorItemButton)?.initialize(data);
}
// ErrorManager extends Component, so it has a node property
const errorManagerNode = (ErrorManager.instance as any).node;
if (errorManagerNode && typeof errorManagerNode.on === 'function') {
errorManagerNode.on('errors-updated', this.onDataUpdated, this);
} else {
// Детали
const field = itemData as SensorDescriptionField;
node = instantiate(this.sensorFieldItemPrefab);
node.getComponent(SensorFieldItem)?.setData(field);
console.warn("Could not subscribe to ErrorManager events - node not found");
}
node.setPosition(
0,
-(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2),
0
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 });
}
}
this._data = flattened;
// Update both filtered and unfiltered views
if (this._filteredData) {
// If we have a filter, reapply it to the new data
const currentFilter = this._filteredData.length > 0 ? this._filteredData[0].sensorName : '';
if (currentFilter) {
this._filteredData = this._data.filter(item => item.sensorName === currentFilter);
this._totalCount = this._filteredData.length;
}
} else {
this._totalCount = this._data.length;
}
this.updateContentHeight();
this.updateVisibleItems();
}
private onScrolling() {
this.updateVisibleItems();
}
private updateVisibleItems() {
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.getTotalItems();
// 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
);
this._content.addChild(node);
this._loadedCount++;
}
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
// Always update if visible range changed
const needsUpdate = 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 their pools
for (const item of this._activeItems) {
this.returnItemToPool(item);
}
this._activeItems = [];
}
private returnItemToPool(item: Node) {
item.active = false;
item.removeFromParent();
// Determine which pool this item belongs to and return it
if (item.getComponent(ErrorItemButton)) {
this.getOrCreateErrorItemPool().put(item);
} else if (item.getComponent(ErrorItemNamedButton)) {
this.getOrCreateNamedErrorItemPool().put(item);
} else if (item.getComponent(SensorFieldItem)) {
this.getOrCreateSensorFieldItemPool().put(item);
}
}
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
let currentPool: NodePool;
if (this._mode === "errors") {
if (this._filteredData) {
currentPool = this.getOrCreateNamedErrorItemPool();
} else {
currentPool = this.getOrCreateErrorItemPool();
}
} else if (this._mode === "details") {
currentPool = this.getOrCreateSensorFieldItemPool();
} else {
return;
}
// Show and position visible items from the correct pool
for (let i = 0; i < itemsToShow; i++) {
const dataIndex = this._firstVisibleIndex + i;
if (dataIndex >= 0 && dataIndex < currentData.length) {
const item = currentPool.get() || this.createItemForCurrentMode();
if (!item) continue;
const component = this.getComponentForCurrentMode(item);
// 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;
}
} 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);
}
}
}
private createItemForCurrentMode(): Node | null {
if (this._mode === "errors") {
if (this._filteredData) {
return instantiate(this.errorItemNamedPrefab);
} else {
return instantiate(this.errorItemPrefab);
}
} else if (this._mode === "details") {
return instantiate(this.sensorFieldItemPrefab);
}
return null;
}
private getComponentForCurrentMode(item: Node): Component | null {
if (this._mode === "errors") {
if (this._filteredData) {
return item.getComponent(ErrorItemNamedButton);
} else {
return item.getComponent(ErrorItemButton);
}
} else if (this._mode === "details") {
return item.getComponent(SensorFieldItem);
}
return null;
}
private getCurrentData(): any[] {
if (this._mode === "errors") {
return this._filteredData || this._data;
} else if (this._mode === "details") {
return this._sensorDescription?.fields || [];
}
return [];
}
private getTotalItems(): number {
return this.getCurrentData().length;
}
private updateContentHeight() {
const totalItems = this.getTotalItems();
this._contentUI.height = totalItems * this._itemHeight;
}
private preserveScrollPosition(callback: () => void) {
const oldOffset = this.scrollView.getScrollOffset();
callback();
this.scheduleOnce(() => {
this.scrollView.scrollToOffset(oldOffset, 0.1);
}, 0);
}
/**
* Фильтрует список ошибок по имени оборудования.
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
*/
public filterBySensor(sensorName: string) {
this._mode = 'errors';
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = `Аварии на ${sensorName}`;
this.loadNextBatch(20);
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();
});
}
/**
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
*/
public resetFilter() {
this._mode = 'errors';
this._filteredData = null;
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = 'Список всех аварий';
this.loadNextBatch(20);
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();
});
}
public showSensorDetails(data: { sensorName: string; fields: SensorDescriptionField[] }) {
this._mode = 'details';
this._sensorDescription = data;
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = `Детали ${data.sensorName}`;
this.loadNextBatch(20);
/**
* Принимает данные описания оборудования и переключает режим отображения в "details".
* @param data Объект с деталями датчика.
*/
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
this.preserveScrollPosition(() => {
this.hideAllItems();
this._mode = "details";
this.header.string = `Детали ${data.sensorName}`;
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields || []
};
this.updateContentHeight();
this._firstVisibleIndex = 0;
this._lastVisibleIndex = 0;
this.updatePoolItems();
});
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
this._mode = 'errors';
this._filteredData = null;
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = 'Список всех аварий';
this.loadNextBatch(20);
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();
});
}
}
}