Compare commits

..

9 Commits

Author SHA1 Message Date
e98a23778b вынес из внешнего редактирования ссылки 2025-05-30 04:42:57 +07:00
3e15603f17 отрисовка префаба в левом списке теперь происходит корректно
(высота списка теперь корректно обновляется при изменении количества ошибок)
2025-05-28 00:57:42 +07:00
adbf4faed0 теперь поведение кнопки с отображением описания
не протекает в другие приборы
2025-05-27 22:10:21 +07:00
1851b2d959 синхронизовал состояние кнопки с отображением
дополнительного описания
2025-05-27 13:58:07 +07:00
895287b145 не протекает состояние кнопки с анимацией
при переключение режимов и датчиков
2025-05-26 20:35:34 +07:00
4104adf0f7 исправил проблему с мерцанием списка характеристик
и аварий перейдя на механизм виртуализации и
использовав механизм отложенной загрузки
2025-05-26 18:13:56 +07:00
da9f2bfbf8 забыл добавить состояние сцены 2025-05-24 04:26:21 +07:00
1d81901b6a избавил от подгрузки по чанкам и перешел на
отрисовку из пула, теперь поведение элементов
 с подсказкой уже лучше, осталось ввести по элементный
 пул .
2025-05-24 04:22:26 +07:00
6a5ba19e3d избавился от инверсии при скролле, добавил скролл
на правый список
2025-05-19 14:53:13 +07:00
12 changed files with 1316 additions and 278 deletions

View File

@ -1032,6 +1032,7 @@
"__id__": 0
},
"fileId": "4aBpvR+bhJdI7i8LzRRtvb",
"instance": null
"instance": null,
"targetOverrides": null
}
]

View File

@ -3633,7 +3633,7 @@
"node": {
"__id__": 105
},
"_enabled": true,
"_enabled": false,
"__prefab": null,
"targetScene": {
"__uuid__": "658bce01-ef82-4cee-8fd2-af66cebdba02",
@ -3642,7 +3642,7 @@
"camera": {
"__id__": 7
},
"_id": "dbrECax/BGr6qrtF+W+fYo"
"_id": "bfWXLDyG5AY7H6p+7j23oL"
},
{
"__type__": "cc.Node",
@ -6161,7 +6161,7 @@
"_priority": 1073741824,
"_fov": 45,
"_fovAxis": 0,
"_orthoHeight": 360,
"_orthoHeight": 364.88687782805425,
"_near": 1,
"_far": 2000,
"_color": {
@ -6411,7 +6411,7 @@
"_string": "Список оборудования",
"_horizontalAlign": 0,
"_verticalAlign": 1,
"_actualFontSize": 21,
"_actualFontSize": 30,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 20,
@ -10888,7 +10888,7 @@
"_string": "button",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 26.166666666666668,
"_actualFontSize": 36.2578125,
"_fontSize": 20,
"_fontFamily": "Arial",
"_lineHeight": 40,
@ -11862,7 +11862,7 @@
"_string": "Список всех аварий",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 14,
"_actualFontSize": 20,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 30,
@ -12218,7 +12218,7 @@
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 131.30711257837382,
"width": 131.29982762335703,
"height": 25.2
},
"_anchorPoint": {
@ -12251,7 +12251,7 @@
"_string": "ScrollView content",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 20.933333333333334,
"_actualFontSize": 29.00625,
"_fontSize": 16,
"_fontFamily": "Arial",
"_lineHeight": 20,
@ -12546,21 +12546,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"
},
{
@ -13918,6 +13919,7 @@
"__id__": 34
},
"spacing": 10,
"visibleItemCount": 15,
"_id": "02Z+hMjflI57Ua6GmQMDOg"
},
{
@ -13975,6 +13977,7 @@
},
"_enabled": true,
"__prefab": null,
"apiUrl": "http://localhost:3030/api/v2/sensors",
"_id": "fd9cjGJCJCmbVairIJtwxV"
},
{

View File

@ -7,8 +7,8 @@ const { ccclass, property } = _decorator;
export class EquipmentManager extends Component {
public static instance: EquipmentManager;
public apiUrl: string = 'http://192.168.0.169:3030/api/v2/sensors';
public apiUrl: string = 'http://localhost:3030/api/v2/sensors';
private _dataList: apiSensors[] = [];
public totalCount: number = 0;
@ -42,12 +42,10 @@ export class EquipmentManager extends Component {
if (data?.items && Array.isArray(data.items)) {
this._dataList = data.items;
this.totalCount = this._dataList.length;
console.log('Данные оборудования обновлены:', this._dataList);
// Триггерим событие, на которое подписывается LazyLoadList
this.node.emit('data-updated');
} else {
console.error('Некорректный формат данных', data);
}
}
} catch (error) {
console.error('Ошибка при загрузке данных:', error);
}

View File

@ -36,7 +36,7 @@ export class ErrorsStore {
*/
public async fetchApiErrors(): Promise<void> {
try {
const response = await fetch("http://192.168.0.169:3030/api/v2/errors");
const response = await fetch("http://localhost:3030/api/v2/errors");
if (!response.ok) {
console.error("ErrorsStore: ошибка при получении ошибок, статус:", response.status);
return;

View File

@ -65,7 +65,8 @@ export class SensorDetailManager extends Component {
.fetchSensorDetails(this.currentSensorName)
.then(data => {
if (data && ErrorLazyLoadList.instance?.mode === 'details') {
ErrorLazyLoadList.instance.showSensorDetails(data);
// Используем updateSensorDetails для обновления без сброса UI
ErrorLazyLoadList.instance.updateSensorDetails(data);
}
})
.catch(console.error);

View File

@ -30,7 +30,7 @@ export class SensorDetailStore extends Component {
this.currentSensorName = sensorName;
try {
const response = await fetch("http://192.168.0.169:3030/api/v2/sensor-details", {
const response = await fetch("http://localhost:3030/api/v2/sensor-details", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sensorName: sensorName })

View File

@ -1,209 +1,779 @@
// 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';
import { MorphButtonWithButton } from '../ux/MorphButtonWithButton';
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;
// Статические поля для сохранения состояния между сценами
private static _savedMode: "errors" | "details" = "errors";
private static _savedSensorDescription: SensorDescription | null = null;
private static _savedFilteredData: ErrorItemData[] | null = null;
@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 _sensorFieldItemPools: Map<string, NodePool> = new Map(); // Пул для каждого датчика
private _activeSensorNames: Set<string> = new Set(); // Отслеживаем активные датчики
private _activeSensorFieldItems: Map<string, Set<Node>> = new Map(); // Отслеживаем активные элементы для каждого датчика
// Active items tracking
private _activeItems: Node[] = [];
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
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 = 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);
const errorManagerNode = (ErrorManager.instance as any)?.node;
if (errorManagerNode) {
errorManagerNode.off('errors-updated', this.onDataUpdated, this);
}
// Clear pools and active items tracking
this._errorItemPool?.clear();
this._namedErrorItemPool?.clear();
this._sensorFieldItemPools.forEach(pool => pool.clear());
this._sensorFieldItemPools.clear();
this._activeSensorNames.clear();
this._activeSensorFieldItems.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(sensorName: string): NodePool {
// Используем один общий пул для всех датчиков
if (!this._sensorFieldItemPools.has('common')) {
const pool = new NodePool();
// Создаем пул достаточного размера
const poolSize = Math.max(this.visibleItemCount, 20);
for (let i = 0; i < poolSize; i++) {
const item = instantiate(this.sensorFieldItemPrefab);
// Сбрасываем состояние кнопок при создании
this.resetSensorFieldItemState(item);
pool.put(item);
}
this._sensorFieldItemPools.set('common', pool);
}
return this._sensorFieldItemPools.get('common')!;
}
private resetSensorFieldItemState(item: Node) {
// Сбрасываем состояние компонента SensorFieldItem
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
sensorFieldItem.resetState();
sensorFieldItem.reinitialize();
}
}
/**
* Полностью очищает все пулы и уничтожает элементы
*/
private clearAllPools() {
console.log('[ErrorLazyLoadList] Clearing all pools');
// Очищаем и уничтожаем элементы в пулах
if (this._errorItemPool) {
this._errorItemPool.clear();
this._errorItemPool = null;
}
if (this._namedErrorItemPool) {
this._namedErrorItemPool.clear();
this._namedErrorItemPool = null;
}
// Очищаем пулы датчиков
this._sensorFieldItemPools.forEach(pool => {
pool.clear();
});
this._sensorFieldItemPools.clear();
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
}
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
// Обновляем отображение в зависимости от режима
if (this._mode === "errors") {
this.onDataUpdated();
} else if (this._mode === "details") {
// Для режима details обновляем размеры и элементы
this.updateVisibleItems(true); // Принудительно обновляем (включая высоту)
}
}
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 });
}
}
const oldDataLength = this._data.length;
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) {
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;
}
}
// Просто обновляем видимые элементы без уничтожения
this.updateVisibleItems();
}
private onScrolling() {
this.updateVisibleItems();
}
private updateVisibleItems(forceUpdate: boolean = false) {
const totalItems = this.getTotalItems();
// При принудительном обновлении всегда обновляем высоту контента
// Также обновляем высоту если изменилось общее количество элементов
if (forceUpdate || this._totalCount !== totalItems) {
this._totalCount = totalItems;
this.updateContentHeight();
}
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);
// 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 OR if forced
const needsUpdate = forceUpdate ||
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
// Создаем копию массива, так как returnItemToPool может изменять _activeItems
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();
// 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)) {
// Для датчиков НЕ возвращаем в пул, а уничтожаем для гарантии чистого состояния
console.log(`[ErrorLazyLoadList] Destroying SensorFieldItem instead of pooling`);
// Удаляем из активных элементов
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem && sensorFieldItem.sensorName) {
const activeItems = this._activeSensorFieldItems.get(sensorFieldItem.sensorName);
if (activeItems) {
activeItems.delete(item);
console.log(`[ErrorLazyLoadList] Removed item from active items for ${sensorFieldItem.sensorName}, remaining: ${activeItems.size}`);
}
}
if (sensorFieldItem) {
sensorFieldItem.resetState(); // Сбрасываем состояние перед уничтожением
}
item.destroy(); // Полностью уничтожаем элемент
}
}
private updatePoolItems() {
const currentData = this.getCurrentData();
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") {
const sensorName = this._sensorDescription.sensorName;
currentPool = this.getOrCreateSensorFieldItemPool(sensorName);
expectedComponentType = "SensorFieldItem";
this._activeSensorNames.add(sensorName);
// Инициализируем Set для активных элементов этого датчика, если его нет
if (!this._activeSensorFieldItems.has(sensorName)) {
this._activeSensorFieldItems.set(sensorName, new Set());
}
} else {
return;
}
// Проверяем совместимость существующих элементов с текущим режимом
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);
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) {
let item: Node | null = null;
if (this._mode === "details") {
// Для датчиков всегда создаем новые элементы
item = this.createItemForCurrentMode();
} else {
// Для ошибок используем пул
item = currentPool.get() || this.createItemForCurrentMode();
}
if (!item) break;
this._content.addChild(item);
item.active = true;
this._activeItems.push(item);
this._activeItemsData.push(null); // Placeholder для новых элементов
// Если это элемент датчика, добавляем его в активные элементы
if (this._mode === "details") {
const sensorName = this._sensorDescription.sensorName;
let activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems) {
activeItems = new Set();
this._activeSensorFieldItems.set(sensorName, activeItems);
}
activeItems.add(item);
console.log(`[ErrorLazyLoadList] Added SensorFieldItem to active items for ${sensorName}, total: ${activeItems.size}`);
}
}
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
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 isNewSensorItem = this._mode === "details" && !oldData;
// Для датчиков проверяем изменения в значениях полей более детально
let dataChanged = false;
if (this._mode === "details" && oldData && newData) {
dataChanged = oldData.name !== newData.name ||
oldData.value !== newData.value ||
oldData.unit !== newData.unit ||
oldData.description !== newData.description;
}
const needsUpdate = isNewSensorItem || !oldData ||
dataChanged ||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
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') {
console.log(`[ErrorLazyLoadList] Updating SensorFieldItem data: ${newData.name}`);
// Для новых элементов используем setData (полная инициализация)
// Для существующих элементов используем updateData (сохранение состояния UI)
if (isNewSensorItem) {
(component as SensorFieldItem).setData(newData);
} else {
(component as SensorFieldItem).updateData(newData);
}
}
break;
}
// Сохраняем новые данные для будущих сравнений
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
} catch (e) {
console.warn("Error updating item component:", e);
}
}
// Позиционируем элемент (это нужно делать всегда для виртуализации)
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 createItemForCurrentMode(): Node | null {
if (this._mode === "errors") {
if (this._filteredData) {
return instantiate(this.errorItemNamedPrefab);
} else {
return instantiate(this.errorItemPrefab);
}
} else if (this._mode === "details") {
// Для датчиков всегда создаем новые элементы для гарантии чистого состояния
if (this._sensorDescription && this._sensorDescription.sensorName) {
console.log(`[ErrorLazyLoadList] Creating fresh SensorFieldItem for ${this._sensorDescription.sensorName}`);
const item = instantiate(this.sensorFieldItemPrefab);
// Сбрасываем состояние нового элемента
this.resetSensorFieldItemState(item);
return item;
}
return null;
}
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();
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) {
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);
// Проверяем, действительно ли меняется фильтр
const isNewFilter = !this._filteredData ||
this._filteredData.length === 0 ||
this._filteredData[0].sensorName !== sensorName;
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется фильтр
if (isNewFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this._mode = "errors";
this.header.string = `Аварии на ${sensorName}`;
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
this._totalCount = this._filteredData.length;
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
/**
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
*/
public resetFilter() {
this._mode = 'errors';
this._filteredData = null;
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = 'Список всех аварий';
this.loadNextBatch(20);
// Проверяем, действительно ли есть активный фильтр
const hasActiveFilter = this._filteredData !== null;
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если был активный фильтр
if (hasActiveFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this.header.string = "Список всех аварий";
this._mode = "errors";
this._filteredData = null;
this._totalCount = this._data.length;
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
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[] }) {
// Проверяем, действительно ли меняется датчик или режим
const isNewSensor = !this._sensorDescription || this._sensorDescription.sensorName !== data.sensorName;
const isModeChange = this._mode !== "details";
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется датчик или режим
if (isNewSensor || isModeChange) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "details";
this.header.string = `Детали ${data.sensorName}`;
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields || []
};
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
/**
* Обновляет данные датчика без сброса UI состояния (для периодических обновлений).
* @param data Объект с деталями датчика.
*/
public updateSensorDetails(data: { sensorName: string, fields: any[] }) {
// Обновляем только если мы в режиме details и это тот же датчик
if (this._mode !== "details" || !this._sensorDescription ||
this._sensorDescription.sensorName !== data.sensorName) {
return;
}
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,
fields: data.fields || []
};
// Принудительно сбрасываем данные отслеживания для принудительного обновления
this._activeItemsData = this._activeItemsData.map(() => null);
// Принудительно обновляем все активные элементы датчика
this.forceUpdateActiveSensorItems(data.sensorName, data.fields);
// Если изменилось количество полей, принудительно обновляем высоту контента
if (oldFieldsCount !== newFieldsCount) {
this.updateVisibleItems(true);
} else {
// Обновляем видимые элементы без принудительного обновления высоты
this.updateVisibleItems(false);
}
}
/**
* Принудительно обновляет все активные элементы конкретного датчика
*/
private forceUpdateActiveSensorItems(sensorName: string, fields: any[]) {
const activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems || activeItems.size === 0) {
console.log(`[ErrorLazyLoadList] No active items found for sensor ${sensorName}`);
return;
}
console.log(`[ErrorLazyLoadList] Force updating ${activeItems.size} active items for sensor ${sensorName}`);
// Обновляем каждый активный элемент
let itemIndex = 0;
for (const item of activeItems) {
if (!item.isValid || !item.active) {
continue;
}
const component = item.getComponent(SensorFieldItem);
if (component && itemIndex < fields.length) {
const fieldData = fields[itemIndex];
console.log(`[ErrorLazyLoadList] Force updating item ${itemIndex}: ${fieldData.name} = ${fieldData.value}`);
// Используем updateData() вместо setData() для сохранения состояния UI
component.updateData(fieldData);
itemIndex++;
}
}
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
this._mode = 'errors';
this._filteredData = null;
this._loadedCount = 0;
this._content.removeAllChildren();
this.header.string = 'Список всех аварий';
this.loadNextBatch(20);
// Проверяем, действительно ли меняется режим
const isModeChange = this._mode !== "errors";
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется режим
if (isModeChange) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "errors";
this.header.string = "Список всех аварий";
this._filteredData = null;
this._totalCount = this._data.length;
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
}
private updateSensorFieldItem(item: Node, data: any, dataIndex: number) {
const component = item.getComponent(SensorFieldItem);
if (component) {
component.setData(data);
}
}
private cleanupUnusedSensorPools() {
// Теперь у нас один общий пул, поэтому просто очищаем неиспользуемые ссылки
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
}
}

View File

@ -1,5 +1,6 @@
import { _decorator, Component, Label, Node } from 'cc'; // <-- добавили Node
import { SensorDescriptionField } from '../stores/SensorDescriptionField';
import { MorphButtonWithButton } from '../ux/MorphButtonWithButton';
const { ccclass, property } = _decorator;
@ccclass('SensorFieldItem')
@ -24,11 +25,72 @@ export class SensorFieldItem extends Component {
@property({ type: Node })
public Morph: Node | null = null;
/** Имя датчика для корректной работы с пулами */
public sensorName: string = "";
private morphButton: MorphButtonWithButton | null = null;
private buttonId: string = "";
private hasDescription: boolean = false;
protected onLoad(): void {
// Сразу прячем контейнер, теперь active доступен
console.log(`[SensorFieldItem] onLoad: ${this.node.name} (${this.node.uuid})`);
// Сразу прячем контейнер, теперь active доступен
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Находим кнопку Morph
if (this.Morph) {
this.morphButton = this.Morph.getComponent(MorphButtonWithButton);
if (this.morphButton) {
this.buttonId = this.morphButton.getButtonId();
console.log(`[SensorFieldItem] Found MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
// Подписываемся на изменение состояния кнопки
const button = this.Morph.getComponent('cc.Button') as any;
if (button) {
button.node.on('click', this.onMorphButtonClick, this);
}
}
}
}
protected onDestroy(): void {
// Отписываемся от событий при уничтожении
if (this.Morph && this.Morph.isValid) {
try {
const button = this.Morph.getComponent('cc.Button') as any;
if (button && button.node && button.node.isValid) {
button.node.off('click', this.onMorphButtonClick, this);
}
} catch (e) {
// Игнорируем ошибки при уничтожении
console.warn('[SensorFieldItem] Error in onDestroy:', e);
}
}
}
private onMorphButtonClick(): void {
if (!this.hasDescription || !this.morphButton) return;
// Ждем завершения анимации кнопки (2 кадра по 0.055 = 0.11 + небольшой запас)
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.15);
}
/**
* Синхронизирует видимость описания с состоянием кнопки
*/
private syncDescriptionWithButton(): void {
if (!this.morphButton || !this.hasDescription) return;
const isShowingDescription = !this.morphButton.getIsQuestion();
console.log(`[SensorFieldItem] syncDescriptionWithButton: button state = ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}, showing description = ${isShowingDescription}`);
if (this.descriptionContainer) {
this.descriptionContainer.active = isShowingDescription;
}
}
/**
@ -36,25 +98,144 @@ export class SensorFieldItem extends Component {
* @param field Объект поля датчика (name, value, unit, description)
*/
public setData(field: SensorDescriptionField): void {
this.setDataInternal(field, true); // Полная инициализация с сбросом состояния
}
/**
* Обновить только данные без сброса состояния UI (для обновлений в реальном времени).
* @param field Объект поля датчика (name, value, unit, description)
*/
public updateData(field: SensorDescriptionField): void {
this.setDataInternal(field, false); // Обновление без сброса состояния
}
/**
* Внутренний метод для установки данных с возможностью сохранения состояния UI
* @param field Объект поля датчика
* @param resetUIState Нужно ли сбрасывать состояние UI (кнопки и описания)
*/
private setDataInternal(field: SensorDescriptionField, resetUIState: boolean): void {
console.log(`[SensorFieldItem] ${resetUIState ? 'setData' : 'updateData'}: ${this.node.name} (${this.node.uuid}), field: ${field.name}, buttonId: ${this.buttonId}`);
// Обновляем основные данные (это всегда нужно делать)
if (this.nameLabel) this.nameLabel.string = field.name;
if (this.valueLabel) this.valueLabel.string = String(field.value);
if (this.unitLabel) this.unitLabel.string = field.unit ?? "????";
const hasDesc = !!field.description?.trim();
this.hasDescription = !!field.description?.trim();
console.log(`[SensorFieldItem] Has description: ${this.hasDescription}, resetUIState: ${resetUIState}, buttonId: ${this.buttonId}`);
// Работаем с описанием
if (this.descriptionLabel) {
this.descriptionLabel.string = hasDesc ? field.description! : "";
this.descriptionLabel.string = this.hasDescription ? field.description! : "";
}
if (this.descriptionContainer) {
this.descriptionContainer.active = hasDesc;
}
// Morph: теперь показываем его только при наличии описания,
// и скрываем, когда описания нет
if (this.Morph) {
this.Morph.active = hasDesc;
if (resetUIState) {
// Полная инициализация - сбрасываем состояние UI
// Всегда начинаем с скрытого описания (кнопка в состоянии question)
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Morph: показываем кнопку только при наличии описания
if (this.Morph) {
this.Morph.active = this.hasDescription;
// Убеждаемся, что кнопка в состоянии question при первом показе
if (this.morphButton && this.morphButton.getIsQuestion() === false) {
console.log(`[SensorFieldItem] Fully reinitializing button to question state for: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
// Принудительно синхронизируем состояние после небольшой задержки
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
}
} else {
// Обновление данных - сохраняем текущее состояние UI
if (this.Morph) {
// Показываем/скрываем кнопку в зависимости от наличия описания
this.Morph.active = this.hasDescription;
// НЕ сбрасываем состояние кнопки, сохраняем текущее
// Только синхронизируем видимость описания с текущим состоянием кнопки
if (this.hasDescription) {
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
} else {
// Если описания нет, скрываем контейнер
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
}
}
}
}
/**
* Сбросить состояние компонента к начальному
*/
public resetState(): void {
console.log(`[SensorFieldItem] resetState: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}`);
// Сбрасываем все данные
this.hasDescription = false;
this.sensorName = "";
// Сбрасываем текст в лейблах
if (this.nameLabel) this.nameLabel.string = "";
if (this.valueLabel) this.valueLabel.string = "";
if (this.unitLabel) this.unitLabel.string = "";
if (this.descriptionLabel) this.descriptionLabel.string = "";
// Скрываем контейнер описания
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Скрываем кнопку и сбрасываем её состояние
if (this.Morph) {
this.Morph.active = false;
if (this.morphButton) {
console.log(`[SensorFieldItem] Fully reinitializing MorphButton state in resetState: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
}
}
/**
* Переинициализация компонента после получения из пула
*/
public reinitialize(): void {
console.log(`[SensorFieldItem] reinitialize start: ${this.node.name}`);
// Переинициализируем ссылку на кнопку, так как она могла измениться
if (this.Morph) {
// Сначала очищаем старую ссылку
this.morphButton = null;
// Получаем компонент заново
this.morphButton = this.Morph.getComponent(MorphButtonWithButton);
if (this.morphButton) {
console.log(`[SensorFieldItem] Before fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
// Используем полную переинициализацию вместо простого resetState
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId();
console.log(`[SensorFieldItem] After fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
console.log(`[SensorFieldItem] Fully reinitialized MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
} else {
console.warn(`[SensorFieldItem] MorphButton component not found on ${this.Morph.name}`);
}
}
// Гарантируем, что описание скрыто
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
}
}

View File

@ -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 = [];
}
}

View File

@ -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;
}
}
}

View File

@ -1,4 +1,4 @@
import { _decorator, Component, Sprite, SpriteFrame, tween, Button } from 'cc';
import { _decorator, Component, Sprite, SpriteFrame, tween, Button, Tween, Node, Color } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('MorphButtonWithButton')
@ -10,13 +10,63 @@ export class MorphButtonWithButton extends Component {
@property(Sprite) targetSprite!: Sprite;
private isQuestion = true;
private buttonId: string = '';
private currentTween: Tween<Node> | null = null;
onLoad() {
this.targetSprite.spriteFrame = this.questionFrame;
// Генерируем уникальный ID для кнопки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] onLoad: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}`);
this.initializeSprite();
}
private initializeSprite() {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
this.isQuestion = true;
}
}
public fullReinitialize() {
console.log(`[MorphButton] fullReinitialize START: ${this.node.name} (${this.node.uuid}), current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем все анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
// Полностью переинициализируем состояние
this.isQuestion = true;
this.currentTween = null;
// Переинициализируем спрайт
this.initializeSprite();
// Генерируем новый ID для отладки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] fullReinitialize COMPLETE: ${this.node.name}, new state: ${this.isQuestion ? 'question' : 'cross'}, buttonId: ${this.buttonId}`);
}
onDestroy() {
// Останавливаем все анимации при уничтожении
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
}
public onClick() {
console.log('MorphButton: onClick вызван');
console.log(`[MorphButton] onClick: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем предыдущую анимацию, если она есть
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
const frames = this.isQuestion
? [this.noiseFrame, this.crossFrame]
: [this.noiseFrame, this.questionFrame];
@ -31,8 +81,66 @@ export class MorphButtonWithButton extends Component {
this.targetSprite.spriteFrame = frame;
});
}
// Меняем состояние только после завершения анимации
tw = tw.call(() => {
this.isQuestion = !this.isQuestion;
console.log(`[MorphButton] Animation complete, new state: ${this.isQuestion ? 'question' : 'cross'}`);
});
// Сохраняем ссылку на текущий tween
this.currentTween = tw;
tw.start();
}
this.isQuestion = !this.isQuestion;
public resetState() {
console.log(`[MorphButton] resetState: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, was: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем любые активные анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
// Останавливаем все tween на спрайте
Tween.stopAllByTarget(this.targetSprite.node);
// Сбрасываем состояние
this.isQuestion = true;
// Принудительно сбрасываем спрайт
this.forceResetSprite();
}
private forceResetSprite() {
if (!this.targetSprite || !this.questionFrame) {
console.warn('[MorphButton] Cannot reset sprite - missing targetSprite or questionFrame');
return;
}
// Метод 1: Прямая установка
this.targetSprite.spriteFrame = this.questionFrame;
// Метод 2: Очистка и повторная установка
this.targetSprite.spriteFrame = null;
this.scheduleOnce(() => {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
console.log(`[MorphButton] Sprite reset complete`);
}
}, 0);
// Метод 3: Принудительное обновление через изменение других свойств
const originalColor = this.targetSprite.color.clone();
this.targetSprite.color = new Color(255, 255, 255, 254);
this.targetSprite.color = originalColor;
}
public getButtonId(): string {
return this.buttonId;
}
public getIsQuestion(): boolean {
return this.isQuestion;
}
}

View File

@ -23,20 +23,20 @@ export class ScrollHandler extends Component {
}
private onDrag(evt: EventTouch) {
const handleSprite = this.scrollBar.handle;
if (!handleSprite) return;
const handleSprite = this.scrollBar.handle;
if (!handleSprite) return;
const barNode = this.scrollBar.node;
const ui = barNode.getComponent(UITransform)!;
const worldPos = evt.getLocation();
const local = ui.convertToNodeSpaceAR(new Vec3(worldPos.x, worldPos.y, 0));
const barNode = this.scrollBar.node;
const ui = barNode.getComponent(UITransform)!;
const worldPos = evt.getLocation();
const local = ui.convertToNodeSpaceAR(new Vec3(worldPos.x, worldPos.y, 0));
const H = ui.height;
const handleH = handleSprite.node.getComponent(UITransform)!.height;
let pct = (local.y + H/2 - handleH/2) / (H - handleH);
pct = clamp(pct, 0, 1);
const H = ui.height;
const handleH = handleSprite.node.getComponent(UITransform)!.height;
let pct = (local.y + H/2 - handleH/2) / (H - handleH);
pct = clamp(pct, 0, 1);
// Прокручиваем ScrollView без анимации
this.scrollView.scrollToPercentVertical(1 - pct, 0);
}
// ПРОПУСКАЕМ инверсию — передаём pct напрямую
this.scrollView.scrollToPercentVertical(pct, 0);
}
}